Read from a file line by line

一世执手 提交于 2019-12-13 05:19:50

问题


How can I read from a text file line by line , then use the same array to save them ..


回答1:


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);
}



回答2:


Reference to getline says that data is appended to the string

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

Try resetting the string after the read

Edit

Each time you call getline, line keeps the old content and adds the new data at the end.

line = "";

Will reset data between each read



来源:https://stackoverflow.com/questions/26953360/read-from-a-file-line-by-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!