逐行读取文件

Read from a file line by line

本文关键字:文件 读取 逐行      更新时间:2023-10-16

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

首先,您似乎在代码中使用了using namespace std;。这是非常不鼓励的。这是我如何使用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.close() 方法是在其析构函数中处理的,所以我们不需要包含它。这更干净,读起来更像英语,而且没有神奇的常数。另外,它使用 std::vector ,这是非常有效的。

编辑:修改,每个元素都带有std::string[]

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)) {
    std::string array[1];
    array[0] = str;
    vec.push_back(array);
}

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

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

尝试在读取后重置字符串

编辑

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

line = "";

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