逐行读取文件 [英] Read from a file line by line
问题描述
如何从一个文本文件中逐行读取,然后使用相同的数组来保存它们。首先,你似乎在代码中使用 using namespace std;
。 这是非常不鼓励的。这是我将如何使用 std :: vector
。首先,您必须导入< vector>
头文件。
std :: ifstream in_file(file.txt);
if(!in_file){...} //处理文件不存在的错误
std :: vector< std :: string> vec;
std :: string str;
//将每行插入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){...} //处理文件不存在的错误
std :: vector< std :: string []& vec;
std :: string str;
//将每行插入到vec
while(std :: getline(in_file,str)){
std :: string array [1];
array [0] = str;
vec.push_back(array);
}
How can I read from a text file line by line , then use the same array to save them ..
Firstly, it seems that you are using using namespace std;
in your code. This is highly discouraged. Here is how I would use std::vector
. First, you have to import the <vector>
header file.
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
's .close()
method is handled in its destructor, so we don't need to include it. This is cleaner, reads more like English, and there are no magical constants. Plus, it uses std::vector
, which is very efficient.
Edit: modification with a std::string[]
as each element:
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);
}
这篇关于逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!