Search code examples
c++stringionewlinecin

I want cin to read until '\n' but I cannot use getline


I have a text file in the following format:

info
data1 data2
info
data1 data2 data3 data4...

The problem is: the count (and length) of the data may be very large and cause run-time problems when getline() is used. So I cannot read the entire line into a std::string. I tried the following:

for(int i=0; i<SOME_CONSTANT ; i++){
    string info, data;

    cin >> info;

    while(cin.peek() != '\n' && cin >> data){
         // do stuff with data
    }
}

However cin.peek() did not do the trick. The info is read into data in the while loop and program messes things up. How can I fix this?


Solution

  • You can try reading character by character.

    char ch;
    data = "";
    cin >> std::noskipws;
    while( cin >> ch && ch != '\n' ) {
      if ( ch == " " ) {
        // do stuff with data
        data = "";
        continue;
      }
      data += ch;
    }
    cin >> std::skipws;