Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 831
Varaquilex Avatar asked Dec 10 '13 18:12

Varaquilex


People also ask

Why CIN Getline is not working?

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.

Can I use CIN with Getline?

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.

Do you need CIN ignore after Getline?

You don't need to use cin. ignore() with getline() . here is the code prior to the trouble... name2 should be an std::string.


2 Answers

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;
like image 130
Abhishek Bansal Avatar answered Oct 13 '22 07:10

Abhishek Bansal


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

like image 25
rubenvb Avatar answered Oct 13 '22 07:10

rubenvb