tags:

views:

92

answers:

4

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?

+1  A: 

Reading input with cin and the extraction operator >> skips whitespace. Instead, read the input line by line and exit when the line is empty.

Greg Hewgill
A: 

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).

Amber
+6  A: 

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 strings rather than char arrays.

JoshD
I disagree with that. `std::istream::getline()` works on raw `char` arrays - not something I'd recommend to novices. The free function `std::getline()`, automatically expanding the string it writes into, is much better for that.
sbi
@sbi: Thanks for the suggestion; I've amended the answer to include it.
JoshD
+3  A: 
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!";
sbi
+1 for putting him on the right track, though I'd feel safer if the loop termination handled a line with optional whitespace.
Tony
thanks for the example, got me going once I figured out I had to have cin.ignore for earlier code lol
russ
@Tony: I'm not sure what you're at. I thought empty lines would terminate the input?
sbi
@sbi: just thinking that a line that looks empty (when in a file) isn't necessarily an empty empty... the int streaming all happily copes with tabs, extra spaces, carriage returns etc., but the `.empty()` test is not as accepting of input. Minor thing though - you've done it to the letter :-).
Tony
@Tony: Ah, so what you're after is that, if needed, a `std::cin >> std::ws;` should be done before reading a line? If so, the current code will at least not let that go undetected. Inputting the integers will fail on an all-whitespace line and an exception thrown.
sbi