Reputation: 1320
I was trying 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 give number of lines, the program exits. I haven't figured out what's going on, so I've decided to ask it here.
Thanks in advance.
Upvotes: 6
Views: 5854
Reputation: 3687
Adding a cin.get()
before cin.get(a, 10)
will solve your problem because it will read the remaining endline in the input stream.
Upvotes: 2
Reputation: 168626
Mixing formatted and unformatted input is fraught with problems. In your particular case, this line:
std::cin >> n;
consumes the number you typed, but leaves the '\n'
in the input stream.
Subsequently, this line:
cin.get (a, 10);
consumes no data (because the input stream is still pointing at '\n'
). The next invocation also consumes no data for the same reasons, and so on.
The question then becomes, "How do I consume the '\n'
?" There are a couple of ways:
You can read one character and throw it away:
cin.get();
You could read one whole line, regardless of length:
std::getline(std::cin, some_string_variable);
You could ignore the rest of the current line:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
As a bit of related advice, I'd never use std::istream::get(char*, streamsize)
. I would always prefer: std::getline(std::istream&, std::string&)
.
Upvotes: 6
Reputation: 2553
I think it is important to know this when you are using cin : http://www.cplusplus.com/forum/articles/6046/
Upvotes: 1