Reputation: 11
I need to convert an array of number characters to integer values, in order to perform math operations in C. When I use atoi(argv[2][count]), it only converts the first digit to an integer. So if argv[2]=123, it only converts the '1' to an integer 1. How can I get '123' to be one integer value, 123? Thanks!
Upvotes: 0
Views: 455
Reputation: 813
atoi is a good function to use, however you can write your own atoi function in C.
int xatoi(char *s)
{
int result=0;
while(*s)
{
result=result*10+(*s-48);
s++;
}
return result;
} the logic behind this is every character '1','2',......'s ascii value is stored for example '1' has ASCII value '49'. please compile above program and check for errors i haven't tested it but i am sure it will work.
please see the link below for your reference http://www.newebgroup.com/rod/newillusions/ascii.htm
Upvotes: 3
Reputation:
argv
is an array of string arrays and so argv[N]
gives you an array. But argv[N][J]
gives you element at position J
of the array stored in argv[N]
. However, it is strange that compiler did not complain about your code because atoi()
function, in fact, expects a pointer (to the null-terminated string) and not a character value. The compiler should have said something like warning: passing argument 1 of ‘atoi’ makes pointer from integer without a cast
. I recommend you not to ignore warnings. Personally I tend to compile the code with the highest warning level and not have a single warning, though our codebase at work is many millions of lines of code.
Also, prefer to use strtol
over atoi
. The problem with atoi
is that it ignores invalid input (i.e. just returns you 0 if there is no problem, without affecting errno
).
Anyway, here is an example of how to grab an array of base 10 integers from a command line:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i;
int n;
char *e;
int *v;
if (argc < 2) {
fprintf(stderr, "Please specify some numbers\n");
return EXIT_FAILURE;
}
n = argc - 1;
v = alloca(sizeof(int) * n);
for (i = 1; i < argc; ++i) {
v[i-1] = strtol(argv[i][i], &e, 10);
if (!v && errno) {
fprintf(stderr, "Cannot convert '%s' into number: %s\n",
argv[i], strerror(errno));
return EXIT_FAILURE;
} else if (*e != '\0') {
fprintf(stderr, "%s is not a number\n", argv[i]);
return EXIT_FAILURE;
}
}
printf("You have entered the following numbers: %d", v[0]);
for (i = 1; i < n; ++i)
printf(", %d", v[i]);
printf("\n");
return EXIT_SUCCESS;
}
Hope it is useful.
Upvotes: 0