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?
Problem with getline() after cin >> The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.
The C++ getline() is an in-built function defined in the <string. h> header file that allows accepting and reading single and multiple line strings from the input stream. In C++, the cin object also allows input from the user, but not multi-word or multi-line input. That's where the getline() function comes in handy.
You don't need to use cin. ignore() with getline() . here is the code prior to the trouble... name2 should be an std::string.
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;
Use std::istream::getline
instead of std::getline
. You can choose your buffer size and delimiter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With