逐行从文件中读取

时间:2014-11-16 03:16:30

标签: c++ fstream

如何逐行读取文本文件,然后使用相同的数组保存它们。

2 个答案:

答案 0 :(得分:2)

首先,您似乎在代码中使用using namespace std;This is highly discouraged.以下是我使用std::vector的方法。首先,您必须导入<vector>头文件。

std::ifstream in_file("file.txt");
if (!in_file) { ... } // handle the error of file not existing

std::vector<std::string> vec;
std::string str;

// insert each line into vec
while (std::getline(in_file, str)) {
    vec.push_back(str);
}

std::ifstream的{​​{1}}方法在其析构函数中处理,因此我们不需要包含它。这更干净,读起来更像英语,并没有神奇的常数。另外,它使用.close(),这非常有效。

修改:修改每个元素std::vector

std::string[]

答案 1 :(得分:0)

对getline的引用表示数据附加到字符串

Each extracted character is appended to the string as if its member push_back was called.

尝试在读取

后重置字符串

修改

每次调用getline时,line都会保留旧内容并在最后添加新数据。

line = "";

将在每次读取之间重置数据