-1

Im a new user of c++ and I am stuck with a problem.

If the input for the int variable 'x' is anything other than a number, then c++ seems to skip the cin associated with the char variable 'y'. I tried to use cin.ignore and cin.clear, but they dont seem to work. Any ideas on how to make the program still ask the value for char 'y' when the value for int 'x' is anything but a number(eg. 'a' '*' '') ?

#include <iostream>
using namespace std;
int main()
{
    int x;
    char y;

    cout << "num: ";
    cin >> x;//int input

    cout << endl;//blank line

    cout << "char: ";
    cin >> y;//char input

    cout << endl;//blank line
    return 0;
}
  • I'm surprised that I couldn't find a duplicate for this in 5 seconds... If it fails to extract, the stream (`cin`) will be in a failed state and any further extractions will also fail (until you `clear()` that state). I'll look further ... Edit: Perhaps [Correct way to use cin.fail()](https://stackoverflow.com/a/17929137/7582247) may help. – Ted Lyngmo Dec 29 '20 at 01:47
  • 1
    https://stackoverflow.com/questions/24504582/how-to-test-whether-stringstream-operator-has-parsed-a-bad-type-and-skip-it – πάντα ῥεῖ Dec 29 '20 at 02:14

1 Answers1

0

Are you passing parameters to ignore? The first parameter is the maximum of chars to be ignored and the second one is the flag that it should stop ignoring after findind it (which in the example below I've put '\n')

cin.clear();
cin.ignore(1000, '\n');

To summarize, the code says: Clear up to 1000 chars or up to the first '\n'.

vmp
  • 2,370
  • 1
  • 13
  • 17
  • 2
    `cin.ignore(std::numeric_limits::max(), '\n');` would be the idiomatic way to clear this up - or avoid it completely by reading line-by-line using `std::getline()` and extract from an `std::istringstream`. – Ted Lyngmo Dec 29 '20 at 01:55
  • Admittedly if you have a trillion characters between you and the end of the line, it's probably not worth parsing them all. Often you can `ignore` a couple hundred and write the file off as totally ed. – user4581301 Dec 29 '20 at 02:40