Reputation: 1700
I have to loops to gather input, the first gathers input into a vector of doubles...
double input;
while (cin >> input)
{
list.push_back(input);
}
and the second gathers input into a vector of ints...
int input;
while (cin >> input)
{
list.push_back(input);
}
The second loop keeps auto-exiting and so I added the following two lines...
cin.clear();
cin.ignore(INT_MAX,'\n'); // I've also tried cin.ignore()
However this has occurred in my output being discarded in the second loop. How can I get both of these to work the way they need to?
Upvotes: 1
Views: 131
Reputation: 154045
The first loop reads until the stream goes bad because there isn't any double
to read from. When the stream has gone bad it won't become good again unless you do something, e.g., using std::cin.clear()
to clear the state flags.
Of course, just clearing the state flags won't make much of a difference because it would have read all viable numbers: the format of valid double
s is a superset of the format of valid int
s (well, OK, unless they are using base 16). That is, you'll need some sort of separator, probably a non-space, non-digit character. Your use of ignore()
should skip over a separator and up to the next newline (although the magic value isn't INT_MAX
but std::numeric_limits<std::streamsize>::max()
).
It is unclear what you are trying to input but if you use something like
1 2 3 exit 4 5 6
the first three values would be read as double
and everything else would be ignored. That is, you may want to be ignore characters a bit more careful, e.g., clear the input and keep trying to read an int
and clear()
and ignore()
until this is successful:
// skip separator:
std::cin.clear();
int input;
while (!(std::cin >> input)) {
std::cin.clear();
std::cin.ignore(); // ignore the next character only
}
do {
list.push_back(input);
} while (std::cin >> input);
Upvotes: 2