Thread: what's wrong with my simple addition code?

  1. #1
    Registered User
    Join Date
    Nov 2016
    Posts
    33

    what's wrong with my simple addition code?

    Good day C gurus!

    Write a C program that asks for 2 integer numbers (a and b) and a character in the sameline. The character is then used to define the operation to perform between the numbers aand b. Then, according to the operation selected by the user, computes and shows theresult of one of the following operations (addition/multiplication/etc....)

    I tried to start with the addition first and here is my code
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main()
    {
       int a;int b; char c;
    
    
       scanf("%d %d ",&a,&b);
       scanf("%s",&c);
      printf("%d %d %s",a,b,&c);
       if(c=='+')
        printf("\n %d + %d = %d",a,b,a+b);
    }
    My code gives me very strange results!!

    1
    3 //Those are the two integers and symoble I inserted
    +

    1 0 + // the compiler has transormed my 3 to 0!!!

    1+0=1 (the final result)

    what's wrong??Many thanks in advance!!

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,509
    Code:
    scanf("%s",&c);
    "%s" is for a string. "%c" is for a single character.

    Fixing this will lead to another problem - here is the reason, along with some solutions: FAQ > How do I avoid a "dangling" newline when reading single character user input? - Cprogramming.com

    Code:
    printf("%d %d %s",a,b,&c);
    Again, you want "%c" for a single character.

    And when printing, you don't need the & before c.

  3. #3
    Registered User
    Join Date
    Nov 2016
    Posts
    33
    Thanks a million Matticus!!
    you saved me from a huge pitffal!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What's wrong with my simple C code?
    By godmoney in forum C Programming
    Replies: 20
    Last Post: 01-03-2011, 10:19 AM
  2. what is wrong in this simple code
    By vikingcarioca in forum C Programming
    Replies: 4
    Last Post: 04-23-2009, 07:10 AM
  3. whats wrong with this very simple code?
    By sway1 in forum C++ Programming
    Replies: 2
    Last Post: 07-06-2008, 12:18 PM
  4. Whats wrong with this simple code?
    By o14v in forum C++ Programming
    Replies: 4
    Last Post: 03-19-2008, 01:46 PM
  5. Simple Code Gone Wrong
    By mrlucky0 in forum C Programming
    Replies: 11
    Last Post: 06-20-2003, 07:47 AM

Tags for this Thread