reading from cin buffer

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <sstream>
#include <string>

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.