TAGS :Viewed: 8 - Published at: a few seconds ago

[ Read from a file line by line ]

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

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

Answer 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