Tom
Tom

Reputation: 23

C - argv stores random values instead of given ones

The program should take three command line arguments of which the first is an arithmetical operand and the second and third numbers on which the operand should be applied This program will print random values.

#include <stdio.h>

int main (int argc, int *argv[])
{
  switch ( (char) * argv[1] )
  {
    case '+' : printf("%d", *argv[2] + *argv[3] );
  }

  return 0;
}

Also, how am I supposed to get as command line arguments different data types? Is using the type cast correct?

Upvotes: 0

Views: 718

Answers (3)

sigvaldm
sigvaldm

Reputation: 643

As others have mentioned, the arguments are read as an array of strings into argv. Thus you must use char *argv[]. Conversion from string to int is performed by atoi. Simply casting a character to an integer will give you the ASCII representation of that character.

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

int main (int argc, char *argv[])
{
    switch ( *argv[1] )
    {
        case '+':
            printf("%d\n", atoi(argv[2]) + atoi(argv[3]) );
            break;
    }

    return 0;
}

To get floating point arithmetic, replace %d with %f and atoi by atof.

Of course you should also add sanity checks. In the very minimum, you should check argc to prevent reading from uninitialized space. See comments.

Upvotes: 0

Bidisha Pyne
Bidisha Pyne

Reputation: 541

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

int main(int argc, char *argv[]) {
  if(argc != 4) {
    printf("Error message");
    printf("USAGE: ./a.out <operand> <number1> <number2>");
    return 0;
  }
  switch(*argv[1]) {
    case '+':
      printf("%d", (atoi(argv[2])+atoi(argv[3])));
      break;
    default:
      printf("Enter valid operand");
  }
}

Upvotes: 1

Scooter
Scooter

Reputation: 7059

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

int main (int argc, char *argv[])
{
  if ( argc > 3 )
  {
    switch ( *argv[1] )
    {
       case '+' : 
          printf("answer: %d\n", atoi(argv[2]) + atoi(argv[3])  );
          break;
       default :
          printf("ERROR: operand %c invalid\n",*argv[1]);
    }
  }
  else 
  {
     printf("ERROR: you must enter operator, plus two operands. e.g.:\n");
     printf("%s + 3 2\n",argv[0]);
     return 1;
  }
}

Upvotes: 1

Related Questions