Search code examples
c++fstream

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 ..


Solution

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