I need to count the numbers to the end of the line, I implemented it with cin.peek ():

int a; while(cin.peek() != '\n') { cin >> a; // some pieces of code } 

But a problem arose: while the lines by type 1 2 3 this code processes correctly, for the same line, but with a space at the end, the program continues. Tell me, please, why such a problem arises, and how to solve it?

  • The input data may not be natural numbers? - Yernar
  • @Yernar can only be integers - junkkerrigan 5:42 pm
  • Why is my answer not suitable? - Yernar pm
  • @Yernar it fits, but does not solve my problem - junkkerrigan

1 answer 1

It turns out this way, because you have a space (s) before '\ n' and accordingly cin.peek () looks at this space and the condition will be true, those will wait for the next number.

If you need to read an indefinite number of numbers in a string, then you can read this string and pass it to std :: stringstream and read further from stringstream, spaces at the end will not interfere.

 string s; getline(cin, s); stringstream inp(s); int a; while (inp >> a) { // some pieces of code } 
  • This is not the answer to the question - AR Hovsepyan