There are several problems with your code. The most fundamental
is that you do two inputs each time through the loop, the first
in the while
, and the second using >>
in the loop. Note too
that the second will skip any spaces, then convert the input to
an integer. If the input cannot be legally converted to an
integer (e.g. the next character is an 'a'
), the input goes
into an error state, and cin.get()
will always return EOF
.
And of course, if you are entering numbers, you can easily
enter more than 25
, and overrun the buffer.
If you just want to enter a sequence of numbers, then:
std::vector<int> fabcd;
int tmp;
while ( std::cin >> tmp ) {
fabcd.push_back( tmp );
}
is all you need. (The numbers must be separated by white
space.) If you want to enter the digits, up until you
encounter a white space, something like the following should
work:
std::vector<int> digits;
int tmp = std::cin.get();
while ( tmp != EOF && ! std::isspace( tmp ) ) {
digits.push_back( tmp /* or tmp - '0' */ );
tmp = std::cin.get();
}
Notice that the results of std::cin.get()
are assigned to an
int
, not a char
. This function returns an int
intentionally, because it must be able to return the out of band
value EOF
. There are a couple of variants on this: if you use
std::cin::peek()
, instead of std::cin::get()
, you'll not
actually extract the character (which you'll have to do in the
loop); and there is also std::get( char& )
, which extract the
character into the given char
, provided it isn't at EOF.
Using this function, the loop would be:
std::vector<int> digits;
char tmp;
while ( std::get( tmp ) && ! std::isspace( tmp ) ) {
digits.push_back( tmp );
}
(You might also want to use std::isdigit
, instead of !
std::ispace
to control the loop.)
EDIT:
One last point: the actual numeric code for a space or whatever
depends on the implementation, and is not necessarily 32.
Also, you'll want to handle tabs and newlines similarly. You
should always use the isspace
, etc. functions. Or if you
really do want to check for a space, and only a space, compare
with ' '
, and not 32.