Reputation: 13425
Was working on a program taking a mathematical expression as a string and then evaluating it and discovered an odd behavior. Given
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){
int ary[4];
char * string = "123+11";
for (int i = 0; i < 3; i++){
ary[i] = atoi(&string[i]);
printf("%d\n", ary[i]);
}
}
I get the output:
123
23
3
Whereas I might have expected I get the output:
1
2
3
Is this part of the atoi()
function?
Upvotes: 0
Views: 85
Reputation: 1149
The answer given by user3758647 is correct. To solve you problem you can use strtok
function which tokenizes the input string based on delimiter.
char* string = "123+23+22";
char *token = strtok(string, "+");
int arr[4], i = 0;
arr[i] = atoi(token); //Collect first number here
while (token != NULL)
{
token = strtok(NULL, " ");
//You can collect rest of the numbers using atoi function from here
i++;
arr[i] = atoi(token);
//Do whatever you want to do with this number here.
}
return 0;
Upvotes: 1
Reputation: 366
This is correct behavior because atoi
takes a pointer to char as input and convert it into int
till it finds "\0
" character.
char * string = "123";
"\0
" in string is present after 123.
For statement:
ary[0] = atoi(&string[0]);
atoi
starts with 1 convert it to int
till 123.
For statement:
ary[1] = atoi(&string[1]);
atoi
starts with 2 convert it to int
till 23.
For statement:
ary[2] = atoi(&string[2]);
atoi
starts with 3 convert it to int
till 3.
Please let me know if it is not clear.
Upvotes: 4