Numbers are read in a loop.
Let us take it step by small step:
This small program will, in a loop, read in integers one by one and print them out.
Till
std::cin >> number
evaluates to
false
(That will happen when the input fails; we enter, say
abcd
when an
int is expected.)
1 2 3 4 5 6 7 8 9 10 11
|
#include <iostream>
int main()
{
int number = 0 ;
while( std::cin >> number ) // loop as long as we have read a number
{
std::cout << "you entered " << number << '\n' ;
}
}
|
Now, let us extend it a little.
1 2 3 4 5 6 7 8 9 10 11
|
#include <iostream>
int main()
{
int number = 0 ;
while( std::cin >> number && number != -99 )
{
std::cout << "you entered " << number << '\n' ;
}
}
|
This will work like the previous program.
In addition, the loop will be exited if we enter
-99
ie.
number != -99
evaluates to
false.
Finally
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
int main()
{
int number = 0 ;
while( std::cout << "enter a number (-99 to quit): " &&
std::cin >> number && number != -99 )
{
std::cout << "you entered " << number << '\n' ;
}
}
|
Works like the program above.
In addition, each time through the loop, it will first prompt the user to enter a number.