Thread: scanf problem

  1. #1
    Registered User
    Join Date
    Nov 2005

    character string problem

    I need to write a program that has the user input a command such as ADD (adds two numbers), SUB(subtracts two numbers), DIV( divides), MUL(multiplies) and then input the two numbers. The user is asked to input all three things at one time. Here is the code.

    int performance(char[], int, int);
    int main()
      int one;
      int two;
      char com[3];
      int FI;
      printf("Enter Instruction:");
      scanf(" %3s %d %d", &com, &one, &two);
      FI =  performance( com, one, two);
      printf("the answer is %d\n", FI);
    int performance(char A[], int B, int C)
      int final;
      char ADD;
      char SUB;
      char DIV;
      char MUL;
      if(A[3] == ADD)
        printf("%d", final);
      if(A[3] == SUB)
        final = B - C;
      if(A[3] == DIV)
        final = B / C;
      if(A[3] ==  MUL)
        final = B*C;
    I am not getting the right answers. I think it has something to do with my if statements.

    please help.
    Last edited by pinkpenguin; 11-28-2005 at 04:00 PM.

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Use a string (a null-terminated array of chars) rather than a single character. Also, it would be better to use fgets and sscanf than scanf.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    > scanf(" %3s %d %d", &com, &one, &two);
    1. 3s needs a char array of 4 elements, so
    char com[4];
    2. You don't need an & with an array, so
    scanf(" %3s %d %d", com, &one, &two);

    > if(A[3] == ADD)
    As well as being outside the array, you don't define ADD either.
    Perhaps you need to include string.h and do
    if( strcmp(A,"ADD") == 0 )

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with RPC and scanf
    By Ricardo_R5 in forum C Programming
    Replies: 11
    Last Post: 01-08-2007, 06:15 PM
  2. Problem with scanf float..
    By aydin1 in forum C Programming
    Replies: 6
    Last Post: 03-06-2005, 01:35 PM
  3. scanf problem
    By gsoft in forum C Programming
    Replies: 3
    Last Post: 01-05-2005, 12:42 AM
  4. problem with looping scanf
    By crag2804 in forum C Programming
    Replies: 6
    Last Post: 09-12-2002, 08:10 PM
  5. scanf problem
    By Flikm in forum C Programming
    Replies: 2
    Last Post: 11-05-2001, 01:48 PM