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):
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');
}