0

I am trying to multiply an input from stdin as well as input from command line argument but getting a type cast error.

#include<stdio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
        int i,x,result;

        printf("Enter a integer:\n");
        x=getchar();

        result=argv[1]+x;

        printf("Result is :%d",result);
        return 0;




}
Jon Abraham
  • 851
  • 3
  • 14
  • 27

4 Answers4

2

Convert the string to integer using atoi() or strtod() before performing addition.

Gopi
  • 19,784
  • 4
  • 24
  • 36
1

Another problem you will see is that the value of 'x' is ASCII, in other words if someone types '1' 'x' will actually contain 49, the ASCII character for '1'. So you need to use atoi() on 'x' as well. Also, you are only getching a single character from stdin so if someone typed in '142' you will only see the '1'!

Apart from these problems your program should work well :-)

JonP
  • 627
  • 6
  • 13
0

argv[1] is type char, so you can't directly add it to the integer. To fix, you can convert argv[1] to a respective int with the atoi function. So your code would look like this:

result=atoi(argv)+x;

If you don't do this and ignore the warning, you will find out that a='1' is not the same as a = 1

Magisch
  • 7,312
  • 9
  • 36
  • 52
0

Use strtol to convert argv[1] to an integer, and scanf to read one from stdin.

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
    int i, x, result;

    if (argc < 2)
    {
        printf("USAGE: %s <integer to add>\n", argv[0]);
        return 1;
    }

    char* ok;
    i = strtol(argv[1], &ok, 10);
    if (*ok)
    {
        puts("Please enter a valid integer as the first command line argument");
        return 1;
    }

    puts("Enter an integer:");
    if (scanf("%d", &x) != 1)
    {
        puts("Invalid input");
        return 1;
    }

    result = i + x;

    printf("Result is: %d\n", result);
    return 0;
}
user4520
  • 3,401
  • 1
  • 27
  • 50