Vector <char*> push_back会覆盖所有条目

Hom*_*mer 1 c++ vector fgets char push-back

我想使用push_back函数用文本文件中的行填充我的向量.但它会用最后一行覆盖所有条目.这是源代码:

  int main() {
    std::vector<char*> lines;
    FILE* file;
    file = fopen("textfile.txt", "r");
    const size_t max_line_length = 1000;
    char line[max_line_length + 1];
    while ( !feof(file)) {
      fgets(line, max_line_length, file);
      lines.push_back(line);
    }
    fclose(file);
 }
Run Code Online (Sandbox Code Playgroud)

希望有人可以提供帮助.

ltj*_*jax 8

你正在覆盖Line,这实际上是你唯一存储的东西,因为你永远不会制作深层拷贝.试试这个:

int main() {
    std::vector<std::string> lines; // <- change this!
    FILE* file;
    file = fopen("textfile.txt", "r");
    const size_t max_line_length = 1000;
    char line[max_line_length + 1];
    while ( !feof(file)) {
      fgets(line, max_line_length, file);
      lines.push_back(line);
    }
    fclose(file);
 }
Run Code Online (Sandbox Code Playgroud)

  • 你仍然会在数组中得到一个额外的行(可能,无论如何---它没有真正指定).`feof`非常像`std :: basic_ios <> :: eof()`; 它的唯一用途是_after_输入失败.循环应该是`while(fgets(line,max_line_length,file))` (3认同)