Reputation: 23
From Australian voting problem:
A bot will keep putting information and it can reach 1000 lines. Example of what he'll enter:
"1 2 3
2 1 3
2 3 1
1 2 3
3 1 2
"
How do I know when he has finished entering information? There is an extra \n at the end and that's my only guess on where to go. cin doesn't seem to detect \n, but getchar() apparently does. It will however get the \n even after the first line of course, and getting it to work has become rather difficult. How do I accomplish this?
Upvotes: 0
Views: 310
Reputation: 12824
I'd suggest using cin.getline
It will get a whole line at a time (ending with \n) and when you get an empty line, you know you're done.
Edit
As suggested by sbi, std::getline is typically a better option for this situation as it utilizes string
s rather than char arrays.
Upvotes: 6
Reputation: 224179
std::string line;
while( std::getline(std::cin,line) && !line.empty() ) {
std::istringstream iss(line);
int i1, i2, i3;
iss >> i1 >> i2 >> i3
if( !is ) throw "dammit!"
process_numbers(i1,i2,i3);
}
if( !std::cin.good() && !std::cin.eof() ) throw "dammit!";
Upvotes: 3
Reputation: 527388
You could instead read a line at a time, and look for the blank line (then later splitting each non-blank line into its 3 numbers).
Upvotes: 0
Reputation: 994669
Reading input with cin
and the extraction operator >>
skips whitespace. Instead, read the input line by line and exit when the line is empty.
Upvotes: 1