Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 449
Vladimir Avatar asked Dec 09 '22 17:12

Vladimir


1 Answers

You can use getline:

#include <string>
#include <iostream>

int main() {
   std::string line;
   if (getline(std::cin,line)) {
      // line is the whole line
   }
}
like image 94
David Rodríguez - dribeas Avatar answered Dec 19 '22 17:12

David Rodríguez - dribeas