[英]Read from a file line by line
我如何才能逐行读取文本文件,然后使用相同的数组保存它们..
首先,似乎您正在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 = "";
将在每次读取之间重置数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.