Teen Programmers Unite  


Return to forum top

C or C++: Convert a character to an integer, etc.

Posted by 142857 [send private reply] at April 15, 2002, 11:28:26 PM

//I don't mean ASCII code here.

#include <stdio.h>
//blah, blah, blah...
char getter;
getter = getchar();

/*NOW: if getter is a number, make it into an int. Could we do this? Something using isalpha(), maybe?*/
/*...actually, maybe use the ASCII code and if it's within the number range (wherever that is--one can check) you subtract something from it...?*/
//Any ideas?

Posted by taubz [send private reply] at April 16, 2002, 12:34:35 AM

You evidentally already know the solution, since you just said it. :)

Posted by vikram_1982 [send private reply] at April 16, 2002, 01:38:26 AM

try the "itoa" and the "atoi" commands.

Posted by buzgub [send private reply] at April 16, 2002, 01:42:03 AM

AFAIK, the C standard specifies that the characters representing the numbers from 0 to 10 shall be in a sequential block starting with 0. Therefore, 'n'-'0', where n can be any number, will always equal n.

Posted by Razvan [send private reply] at April 20, 2002, 02:54:25 AM

If I understood your question, you want to read a number as a character and then convert it to an int that has the value of the number red. The solution I propose is:

-find the ASCII code for 1.

You can do this by writting a simple program that contains:
int i;
printf("%d = %c",i,i);

-then you do something like this:

getter-=ascii_code_for_1; // a-=b is equivalent to a=a-b;
// (just in case there is
// somebody that doesn't know)

This will still be a char, but it contanis the value you need, so you can assign this value to an int variable.

I don't have time to test this, but I think I used this in one of my programs a long time ago, and it should work. If it doesn't please tell me. It's an interesting problem.

Posted by webdesign11 [send private reply] at April 20, 2002, 07:54:21 AM

The ASCii values for 0-9 are 48-57 (or, in hexadecimal "translation", 30-39).

Hope that helps!

Happy coding! :)

Posted by Psion [send private reply] at April 20, 2002, 09:27:20 AM

It's not advisable to ever type ASCII codes into your programs. Instead, simply use '0' for the ASCII code for 0, etc.. This makes things much more portable.

You must be logged in to post messages and see which you have already read.

Log on
Save for later automatic logon

Register as a new user
Copyright TPU 2002. See the Credits and About TPU for more information.