Input validation problem

Hi, I am trying to do a simple if/else input validation but the codes i used only seem to work one way.
The code will work if I want a number and the user input a letter, but it will not work if I ask the user to enter a letter and they input a number.

If i change char to int , it will work as normal, but if I leave it as char, the program will think there are no problems.

#include <iostream>

using namespace std;

int main ()
{
char character;

cout << "Enter a letter: ";
cin >> character;
if (cin.fail())
cout << "failed" << endl;


system ("pause");
return 0;
}
Char variable can store either a character or integer. (because char will treat whatever user input as a char variable).

but int variable can store only a integer, so if they enter a character , it shows error.

Do I make u clear?
Read in the char and then verify that it is alphabetic:
http://www.cplusplus.com/reference/std/locale/isalpha/

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <locale>

int main()
{
    char ch ;
    std::cout << "enter an alpha character: " ;
    if(  std::cin >> ch && std::isalpha( ch, std::cin.getloc() ) )
          std::cout << "ok.\n" ;
    else
          std::cout << "failed.\n" ;
}



Topic archived. No new replies allowed.