在结构中存储可变大小的字符串

dev*_*vin 0 c++ string

我正在使用流读取C++中的文件,特别是fstream,而不是ifstream.

blah blah blah\n
blah blah\n
blah blah blah blah \n
end
Run Code Online (Sandbox Code Playgroud)

这一遍又一遍地重复

  1. 每行中有多少个blah,
  2. 每一端之间的线数恒定,end是这里的分隔符

我想读取一组数据,然后将其存储在C样式结构的字符数组中.我开始尝试使用getline(),但分隔符只能是一个字符,而不是三个字符.我显然不能尝试使用read()读取一定数量的字节,因为每个集合的数字都不同.

所以我对这里最简单(也是最强大)的事情感到震惊.我应该调用getline直到找到'end'字符串,同时反复追加每个字符串?

我尝试了一个2D字符数组,但我复制到它有点痛苦.我可以在这里使用strncpy吗?我认为这不起作用

char buf[10][10];
strncpy(buf[1], "blah blah",10);
Run Code Online (Sandbox Code Playgroud)

我在这里有一些想法,但我不确定哪一个(或者我没有的那个)是最好的.

编辑:所以这是一个网络应用程序,因此char数组(或字符串)的大小应始终相同.此外,结构中应该没有指针.

相关问题:char数组和std :: string存储在内存中的方式是一样的吗?我总是在std :: string上有一些开销.

GMa*_*ckG 7

好吧,你说"在一个C风格的结构",但也许你可以使用std::string

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

int main(void)
{
    std::fstream file("main.cpp");
    std::vector<std::string> lines;

    std::string line;
    while (getline(file, line))
    {
        if (line == "end")
        {
            break;
        }

        std::cout << line << std::endl;
        lines.push_back(line);
    }

    // lines now has all the lines up-to
    // and not including "end"

/* this is for reading the file
end

some stuff that'll never get printed
or addded blah blah
*/
};
Run Code Online (Sandbox Code Playgroud)

  • 您的文件读取逻辑是错误的 - 考虑如果文件为空会发生什么.Coincedentally,我刚刚在http://punchlet.wordpress.com/上发表了关于这个问题的博客 (2认同)