Click here to Skip to main content
15,945,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am executing my c language program in IDE TurboC3.
Non working code is as follows

#include<stdio.h>
#include<conio.h>
void main()
    {
    int i, j, t;
    char opt;
    clrscr();
    printf("Enter two values" );
    scanf("%d", &i);
    scanf("%d", &j);
    printf("\n\n press + for sum\n");
    printf("press * for mult\n");
    printf("print - for subtract\n\n");
    scanf("%c", &opt); // code that is creating problem //
    switch(opt)
        {
        case '+':
            {t=i+j;
            printf("\nsum =%d", t);
            }
            break;
        case '*':
            {t=i*j;
            printf("\nproduct =%d", t);
            }
            break;
        case '-':
            {t=i-j;
            printf("\ndifference =%d", t);
            }
        break;
        default:
            printf("\ninvalid choice");
        }
    getch();
    }


[edit]Code block corrected, indentation added - OriginalGriff[/edit]

What I have tried:

The correction that helped me execute the code is as follows

C++
scanf(" %c", &opt); // code without problem //


i.e. i have inserted a space between " and %c and the code worked.

Please help me understand the difference.
Posted
Updated 8-Jun-17 21:05pm
v2

1 solution

The difference is that scanf uses the format string literally: the need for a space implies that your input is not '+' but has whitespace before it. "%c" is a scanf "special" code: it does not skip whitespace characters at all (unlike "%d" which does). So when your user entered the two values, the terminator was probably "left in the buffer" and returned as the first character instead of the '*' or '+' that the user typed.

To be honest, you'd probably be better off using getch and a loop, with a specific "exit" character instead of reading one char and stopping.
Personally? I'd prompt for each number on a separate line, read it as a char array, and scan that into a number - that way I could cope with user input errors instead of crashing as your code will. Then I'd use getch for the operator.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900