I want cin to read before '\ n', but I can't use getline

I have a text file in the following format:

info data1 data2 info data1 data2 data3 data4... 

The problem is that the amount (and length) of data can be very large and cause run-time problems when using getline() . Therefore, I cannot read the entire string in 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. Information is read into data in a while loop and runs programs. How can i fix this?

+7
c ++ string io newline cin
source share
2 answers

You can try to read 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; 
+7
source share

Use std::istream::getline instead of std::getline . You can choose the size and buffer delimiter.

+3
source share

All Articles