wrong input handling

Hi can you help me with my code. What I want to happen is it loops when it enters an invalid input, so far so good except when I enter something like "4a" it accepts "4" and stores "a" for another input. What do I have to add in my code so that it invalidates "4a" as a whole? Thanks in advance.
1
2
3
4
while (cout<<"Enter the first number: " && !(cin>>first)){
	cin.clear();
	cin.ignore(1000, '\n');
	cout<<"Invalid input. Please re-enter. \n";
Last edited on
Probably be better to use a do while loop or a recursive function for this, but about your problem, if first is an int then cin will only grab the first int. You will probably have to store the input as a string and then validate it and extract the int.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using std::cout; using std::cin;
int main()
{
    cout << "Enter a number: ";
    for(int n; cin >> n; ) {
        cout << "And again: ";
    }
    cout << "\nPress enter to continue . . .\n";
    cin.get();
}


Enter a number: 214
And again: 7564
And again: 9786
And again: 123
And again: 5342
And again: 4a
And again: 
Press enter to continue . . .


http://cpp.sh/6ybk6
Topic archived. No new replies allowed.