This is just an at home assignment so i can expand my knowledge of C++. what i am trying to do is write a series of numbers in console then print out how many positive and negative number there are.

for example
Input = 2 7 6 -2 -5 23 -2
Output = Total positive numbers = 4 Total negative numbers = 3

The problem is i do not know how to loop cin. while cin has a number in its buffer then continue else break out of loop.

i understand that while(cin >> buffer) does not work and causes a endless loop but i dont know of any function to check the buffer for cin

 ``12345678910111213141516`` ``````int main(){ int pos, neg, zero, buffer; cout << "Input series of number:"; while(cin >> buffer){ if(buffer > 0) pos++; else if (buffer == 0) zero++; else neg++; } cout << "Total positive numbers = " << pos << ": Total negative numbers = " << neg << ": Total zeros = " << zero; } ``````
It looks like you want to end your input with a newline, so use getline and then parse the string you extracted for the numbers.

Alternately, keep the code you have and just use non-numeric input to end the loop.

 ``123456789101112131415161718192021222324252627282930`` ``````#include #include #include using namespace std; int main() { std::cout << "Input series: "; std::string line; std::getline(std::cin, line); std::istringstream is(line); int n, pos = 0, neg = 0, zero = 0; while (is >> n) { if (n > 0) ++pos; else if (n < 0) ++neg; else ++zero; } std::cout << "positive numbers: " << pos << '\n'; std::cout << "negative numbers: " << neg << '\n'; std::cout << "zeros: " << zero << '\n'; }``````
nice, very cleaver thank you
Topic archived. No new replies allowed.