Cin ignore bad input completely

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  try
		{
			int code = 0;

			std::cout << "Please Enter 8 digit number: ";
			std::cin >> code;
			if (std::cin.bad()||std::cin.fail())
			{
				std::cin.clear();
				std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
				std::cout << "Recieved code that is not an integer or convertable to an integer" << std::endl;
			}

			GTIN_8 gtin(code);
			
			std::cout << gtin << std::endl;
			system("pause");
		}
		catch (const std::exception& exception)
		{
			std::cout << exception.what() << std::endl;
		}
		catch (...)
		{
			std::cout << "An unknown error occurred, please try again" << std::endl;;
		}
	}


so Basically I've got this, it works fine when I enter something like aab or aa3
but when I enter something that starts with a number, like 1ab it passes the 1 to the function, which I don't want - I would like to completely ignore the imput and try again

How would I do this?
Last edited on
You should use cin.peek() to check for garbage characters remaining in the cin stream.
Topic archived. No new replies allowed.