define String to number

Hi

I want to Define when user enter a character. the character return a number . for example when user enter "A" this character define 1
what?
Hi
for example when user enter A . the Compiler return 1
hi
#define a 1;
int main()
{
char st;
cin >> st; // for example a
cout << st ; // the output is a

}
I want the output is 1
Like this?
3
4
5
6
7
8
9
10
int main()
{
    char st;
    cin >> st;
    if ( st == 'a' )
        cout << 1 ;
   return 0;
}
http://www.cplusplus.com/doc/tutorial/control/#if
No :(
Well then what do you want? You can't output a character as a number with cout.
1
2
3
4
char input1 = 'A';
char input2 = 'b';
std::cout << input1 - 'A' + 1 << std::endl ;
std::cout << input2 - 'A' + 1 << std::endl ;


Here's one interpretation, which is warmer, though likely not quite what OP is looking for.
For starters you can convert any character to an integer. Assuming you have an ANSI character you can use atoi. Personally I don't like this, it always seems a bit too C like to me, but it works (I'm sure theres an alternative, I know there is for c# etc.)

int char_ansi_id = atoi(entered_char);

Now, if it was upper case: A=65-Z=90. Lower case: a=97-z=122

Source: http://www.alanwood.net/demos/ansi.html

int input_val = 0;

if (char_ansi_id >= 65 && char_ansi_id <= 90)
input_val = char_ansi_id - 64
else
input_val = char_ansi_id - 97


Obviously there would need to be som error checking thrown in i.e. if the character entered isn't in those bounds. But I'm sure you can handle that.
Don't expect that code to compile by the way, its was meant simply as a guider not a complete homework solution.
I think he means something like:
1
2
3
4
5
6
7
8
int main()
{
    char st;
    cin >> st;
    if ( st == 'a' )
        return 1;
   return 0;
}


But if you really mean that the compiler should return a code, idc...
closed account (jwC5fSEw)
1
2
char a = 'a';
cout << a - '0';


This outputs 49. Doing the same with 'b' outputs 50, with 'c' outputs 51, and so on. If you want the lower-case alphabet to correspond with numbers starting from 1, you could just use (a - '0') - 48.
Last edited on
ok Thank you
Topic archived. No new replies allowed.