Help with error input

Here i get input for accNum and gives out error message when the input is not an integer. However, whenever an alphanumeric input is entered (integer followed by alpha), the program skips the error message and continues next lines of codes.

So what's wrong with my code here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  int accNum;
  cout << "\nPlease enter Account Number." << endl;
	while (true)	// loops until valid account number is entered
	{
		cin >> accNum;
		if (!cin)
		{
			cout << "\nERROR! \nPlease enter a valid Account Number. (Numbers only)" << endl;
			cin.clear();
			cin.ignore(100, '\n');
		}
		else
		{
			break;
		}
to make this work you would have to input as a string and validate the string.

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
28
29
30
31
32
33
34
35
36
37
38
#include <string>
#include <iostream>
#include <cctype>

bool isInteger(const std::string &input);
int main()
{
    std::cout << "Please enter an integer: ";
    std::string input;
    std::getline(std::cin, input);
    std::cout << std::endl;

    while(!isInteger(input))
    {
        std::cout << "Error invalid input please try again" << std::endl;
        std::cout << "Please enter an integer: ";
        std::getline(std::cin, input);
        std::cout << std::endl;
    }


    std::cout << "The integer was " << input << std::endl;
    std::cin.ignore();
    return  0;
}

bool isInteger(const std::string &input)
{
    if(input.empty())
        return false;

    for(const auto& element: input)
        if(!isdigit(element))
            return false;

    return true;
}


Last edited on
The cin >> operator stops when it encounters a non-numeric. That is not a fail condition, therefore you take the else clause. Because it encountered leading numerics, those were converted and the >> operator is satisfied.
Thanks.
But I've got another problem.
I have a switch statement which takes char input to be evaluated.
It has the same problem as the one above, but how can I do it at the default case? (or is it no way for switch statement?)

skips the default when input is (r2, re, rr, etc.):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
char code;
switch (code)
{
    case 'R':
    case 'r':
          cout << "Code is R" << endl;
          break;
    case 'L':
    case 'l':
          cout << "Code is L" << endl;
          break;
    default:
          cout << "Error!" << endl;
}
Last edited on
Nvm. Figured it out....
Topic archived. No new replies allowed.