Cin.get () in a loop

I tried to read from standard input. The first line is the number of lines that I will read. The lines that I read next will be printed again. Here is the code:

#include <iostream> using namespace std; int main() { int n; cin >> n; for (unsigned int i = 0; i < n; ++i) { char a[10]; cin.get (a, 10); cout << "String: " << a << endl; } return 0; } 

When I run it and output the number of lines, the program exits. I did not understand what was happening, so I decided to ask about it here.

Thanks in advance.

+6
source share
3 answers

Mixing formatted and unformatted input is fraught with problems. In your particular case, this line:

 std::cin >> n; 

consumes the number you dialed but leaves '\n' in the input stream.

Subsequently, this line:

 cin.get (a, 10); 

does not consume data (since the input stream still points to '\n' ). The next call also does not use data for the same reasons, etc.

Then the question arises: "How can I use '\n' ?" There are several ways:

You can read one character and throw it away:

 cin.get(); 

You can read one whole line, regardless of length:

 std::getline(std::cin, some_string_variable); 

You can ignore the rest of the current line:

 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 

As some related tips, I would never use std::istream::get(char*, streamsize) . I always prefer: std::getline(std::istream&, std::string&) .

+6
source

Adding cin.get() to cin.get(a, 10) will solve your problem because it will read the remaining final line in the input stream.

+2
source

I think it is important to know this when you use cin: http://www.cplusplus.com/forum/articles/6046/

+1
source

All Articles