This code is from the book Data Structures and Problem Solving in C++(2003)
void getInts( vector<int> & array )
{
int itemsRead = 0;
int inputVal;
cout << "Enter any number of integers: ";
while( cin >> inputVal )
{
if( itemsRead == array.size( ) )
array.resize( array.size( ) * 2 + 1 ) ;
array[ itemsRead++ ] = inputVal;
}
array.resize( itemsRead ) ;
}
int main()
{
vector<int> array;
getInts( array ) ;
for( int i = 0; i < array.size( ) ; i++ )
cout << array[ i ] << endl;
return 0;
}
When I type a number in the console and press enter, the program does nothing. After that if I type CTRL+Z as EOF the program gives me the number that I typed. Since I’m resizing the vector and giving inputValue to each part of it, I expect to see many numbers instead of one, as much as the program generates before I type CTRL+Z, but that doesn’t happen. The vector’s size seems to be 1 after all. What is the reason for this?
Also my other question is, when I use the while loop as
while( cin >> inputVal )
Will the program work until I type CTRL+Z. Or typing 0 would do the same?
The while loop will continue while cin can read integers from the terminal. It trys to read an integer every time you press enter.
Each read integer is appended to the vector.
If something other than an integer is entered, the fail bit on cin will be set.
cin >> inputValreturns an istream, which providesoperator void* (), which will return0if the fail bit is set.That’s why the while loop breaks out if you enter something other than an integer eg. ‘q’