How to read a file line by line to a string type variable?

17,150

Use std::getline:

std::string s;
while (std::getline(file, s))
{
    // ...
}
Share:
17,150
ufk
Author by

ufk

Programmer, Administrator, Gamer and Musician

Updated on June 04, 2022

Comments

  • ufk
    ufk almost 2 years

    I'm trying to read a file line by line to a string type variable using the following code:

    #include <iostream>
    #include <fstream>
    
    
    ifstream file(file_name);
    
    if (!file) {
        cout << "unable to open file";
        exit(1);
    }
    
    string line;
    while (!file.eof()) {
        file.getline(line,256);
        cout<<line;
    }
    file.close();
    

    it won't compile when I try to use String class, only when I use char file[256] instead.

    how can I get line by line into a string class?