Public Group

# Converting a char to an int

This topic is 4970 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I am currently trying to figure out how to convert a char into an int. Here is my code:
p2.y_pos = buffer;
//p2.y_pos is an int and buffer is a char


I know how to convert an int into a char and I tried doing it backwords but It will not work, atleast while type-casting it. What can I do?

##### Share on other sites
You should be able to assign a char to an int without any problems.

##### Share on other sites
It depends how you are trying to convert the value. Do you want "10" to be converted to 10? or do you want it to be converted to whatever the value of 10 is in ascii? If you want "10" to go to 10, then use the atoi() function, it is in stdlib.h. It converts a character buffer to integers.

##### Share on other sites
hmm...

well for char to int a better conversion technique
would be to use the atoi() function rather than typecasting.

you could also use itoa() function to convert an int to a
string:

char str[10];
int i = 50;

str = itoa(i, str, 10);

where i is the number to be converted,
str is the char* buffer,
and 10 is the size of the char* buffer

hope that helps

##### Share on other sites
beat you by 12 seconds :)

Hey thrust,

##### Share on other sites
from the name of your variable, buffer, I would assume your data is actually not contained in a 'char', but more precisely in a char array ( 'char[]' or '*char' ).

int atoi(const char *nptr);
From stdlib.h, it would do the job for a char array.

p2.y_pos = atoi(buffer);

##### Share on other sites
hello,
how are you :)?
try to use these tow functions
atoi(char value); =to convert from cahr to int
and
atof(char value); =to convert from cahr to float
you should you this header stdlib.h
bye

1. 1
2. 2
3. 3
Rutin
22
4. 4
frob
18
5. 5

• 33
• 13
• 10
• 10
• 12
• ### Forum Statistics

• Total Topics
632569
• Total Posts
3007121

×