Search code examples
c++filestliofstream

How to read the whole lines from a file (with spaces)?


I am using STL. I need to read lines from a text file. How to read lines till the first \n but not till the first ' ' (space)?

For example, my text file contains:

Hello world
Hey there

If I write like this:

ifstream file("FileWithGreetings.txt");
string str("");
file >> str;

then str will contain only "Hello" but I need "Hello world" (till the first \n).

I thought I could use the method getline() but it demands to specify the number of symbols to be read. In my case, I do not know how many symbols I should read.


Solution

  • You can use getline:

    #include <string>
    #include <iostream>
    
    int main() {
       std::string line;
       if (getline(std::cin,line)) {
          // line is the whole line
       }
    }