Pages: [1]   Go Down
Author Topic: Converting a char into an int  (Read 460 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 9
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello,

I'm trying to convert the content of a char array (made of numbers) into an int (or at least an array of integers); something like passing data from char serialNum[n] to int calculateNum[n].

The atoi() function from the stdlib library seems like it could do the trick but i havn't been able to use it properly so far.

Thanks,

Logged

Austin, TX
Offline Offline
Jr. Member
**
Karma: 1
Posts: 94
Shh! I am hunting wabbit. Killlll the wabbit!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

What do you mean by a character array?

Do you mean

char serialNum[] = { '1', '2', '3', '4', '5' }

or

char serialNum[] = "123456";

If you mean something like the first, then that would be the source of the problem with the atoi function.  This function expects to receive a 'c' language string which has a '\0' as the last character of the array.  If you were to look at the memory map for the second version you would see this terminating null.

value = atoi(serialNum)  should work for the second definition of serialNum.

If the first definition was modified to:

char serialNum[] = { '1', '2', '3', '4', '5', '\0' }

It would work also.
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 9
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

This is great.
I meant  char serialNum[] = { '1', '2', '3', '4', '5' }.
Putting '\0' manually at the end of the array did it, i just added
serialNum[5] = '\0'
and the atoi function now runs properly.
Thank you very much!
Logged

Pages: [1]   Go Up
Jump to: