While condition (cin != 0)

Hello everyone im new to c++ programming and just discovered this great site. Maybe one day i will be able to help other beginners like me.
I do apology in advance for my english knowledge.
I did search for an answer on the web but i cant get out of this...
I have to implement this problem:
Get as input ten integers and quit if the user chooses 0.


int main () {
int const length = 50;
int array[length];
cout << "Input a sequence of integers, digit 0 when done : " << endl;
int index = 0;
while (!(cin >> 0)){
cin >> array[index];
i++;
}

cout <<"Your array is: " << endl;

for(index = 0; index < length; index ++){
cout << array[index];
}



system("pause");
}

I Cant figure out how to stop the sequence if input is 0.
Last edited on
the >> operator takes a value out of cin and puts it in whatever variable is on the right side.

So: cin >> foo; takes a value out of cin and put it into the 'foo'.

cin >> 0; does not work because 0 is not a variable, therefore cin cannot put a value into it. This will give you a compiler error.

What you need to do is check the variable after you've taken the number from cin.

1
2
3
4
5
6
7
int foo;
cin >> foo;  // put the number in 'foo'

if(foo == 0)  // was the number zero?
{
  //...
}
Get as input ten integers and quit if the user chooses 0.


You have three conditions to check:
1) the number of integers that were input (if 10, you're done)
2) whether the input is an integer (if it's a word, you didn't say what to do, I'll assume you're done)
3) the value entered (if zero, you're done)

This can be expressed in a while loop like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
int main()
{
    std::vector<int> v;

    int n;
    while(   v.size() < 10   // while there are less than 10 values entered
          && (std::cin >> n) // and an integer can be read from the input
          && n != 0 )        // and the value entered isn't zero
    {
        v.push_back(n); // remember the value
    }

    std::cout << "The values that were entered: ";
    for(auto n: v)
        std::cout << n << ' ';
    std::cout << '\n';
}

live demo (try different inputs): http://ideone.com/9LJqwc
Last edited on
thx alot for your replies, im trying to understand what you said and apply it !
Topic archived. No new replies allowed.