user1411601
user1411601

Reputation: 23

argv reads irrelevant charaters in C

I am learning C programming. My program reads irrelevant numbers than what I supply. Any help? Where am I missing?

#include <stdio.h>

main(int argc, char argv[])
{
    int i,sum, digit;
if(argc == 1)
{
    printf("\n No arguments specified");
    return 0;
}
for(i=1;i<argc;i++)
    {
    digit = argv[i];
    printf("Argument is: %d", digit);
    //sum += argv[i];
    }
printf("The sum of all numbers is: %d", sum);
return 0;
}

Subbu

Upvotes: 1

Views: 153

Answers (4)

unwind
unwind

Reputation: 399703

Your main() is wrong. It should be:

int main(int argc, char *argv[])
                        ^
                        |
                    IMPORTANT!

Since the argument vector is an array of string pointers, not an array of characters.

Then, you're invalidly converting the arguments to integer, you need to call e.g. strtol() or sscanf() to do so. This conversion is necessary since the arguments are passed to your program as an array of strings, and the string "42" (for instance) is very different in C from the number 42.

Note that both the conversion functions I mentioned make it possible to detect if they failed; for instance if the user gives your program non-numerical arguments it's important to detect that and not go ahead and treat them as numbers.

Upvotes: 8

Hui Zheng
Hui Zheng

Reputation: 10224

main(int argc, char argv[]) should be int main(int argc, char *argv[])

main's return value indicates how the program exited, hence it should be explicitly set to int. main's second arguments argv means "argument vector", hence its type should be char *[] or char **.

Upvotes: 1

asc99c
asc99c

Reputation: 3905

You are reading from argv as an integer - you will always get strings in the argv array - it should be defined as char* argv[]. Consider using atoi( argv[i] ) to get the integer value.

Upvotes: 0

MOHAMED
MOHAMED

Reputation: 43518

argv[i] is a pointer to a string and not integer. Strings in c are a char arrays

so your program should be

digit = atoi(argv[i]);

atoi() allow to convert string to an integer and it's from #include <stdlib.h>

Upvotes: 1

Related Questions