checking of alphabet or digit.

#include<iostream>

using namespace std;

int main()
{
int a;

cin>>a;

if (cin.fail())
{
cout<<a<<" "<<"is an alphabet"<<endl;
}

else
{
cout<<a<<" "<<" is a digit"<<endl;
}

return 0;
}

if cin.fail, it will have an output 0is an alphabet.How can i change the code, so the cin a, will come out?
It's because int-type variable can hold only integers and not characters or any other data type. Use string instead, then you can do whatever you want with the input, you can extract whatever you want from the string and convert it to other data types.

For example, this will delete any non-numeric character from a string, then convert the text to int-type data (using "atoi") and assign it to int-type variable.

1
2
3
4
5
6
7
8
string input;
cin >> input;
for (int i = 0; i < (int)input.size()-1; ++i) {
if(!isdigit(input[i])) {
input.erase(input.begin()+i);
--i;
}
int num = atoi(string.c_str());


To use strings, you have to #include <string> header

The function isdigit is a bit troublesome though when it comes to more rare characters. Use this instead (add the code at the beginning of your program):

1
2
3
bool isDigit(char sign) {
return sign >= '0' && sign <= '9';
}


I didn't test any of the code above, so there might be some syntax errors. But I think it should work.
actually this is the extra exercise given by our tutor.He said that cant used the isdigit or isalpha to check.Anyway, he gives us the solution d.It is more on ASCII code.thanks for ur help:)
If you have to do this without functions (even your own), and use ASCII codes, then write this:

1
2
3
4
5
6
7
8
string input;
cin >> input;
for (int i = 0; i < (int)input.size()-1; ++i) {
if(!(input[i] >= 48 && input[i] <= 57)) {
input.erase(input.begin()+i);
--i;
}
int num = atoi(string.c_str());


This is for digits. For alphabet use different ASCII codes (65-90 uppercase, 97-122 lowercase).
You have to know that character '0' just means the number 48 (not literally). For example, you could write

1
2
char ch = '0'
int num = (int)ch;


which would assign the number 48 to num. Some compilers wouldn't even need the cast (the "(int)" thing) to convert the char-type data to int-type.
All built-in data types can be implicitly converted to one another. All compilers therefor support this casting. A different way is to cast it directly when you're outputting (useful for debugging):
1
2
3
4
5
6
#include <iostream>

int main()
{
    std::cout << int('0');
}
There are standard functions for this, see cctype header:
http://www.cplusplus.com/reference/clibrary/cctype/

@Fresh Grass
Don't use ASCII codes directly in your code. It makes it hard to read, and it won't work on systems which don't use ASCII.
I don't use ASCII codes myself, he just said his tutor used ASCII, if I understood correctly.
Topic archived. No new replies allowed.