I created a program of using 'switch' statement to make a simple calculator. If I first take the integer output & then the operator output, the value of b is always shown '0'. (the code is given here) However, if I first take the operator output, the program works just fine. What may be the reason for this? Thanks.
int a;
int b;
char sign;
printf("Enter two required integers: ");
scanf("%d", &a);
scanf("%d", &b);
printf("Enter the operator(+ or - or * or /): ");
scanf(" %s", &sign);
switch(sign){
case '+': printf("The summation of %d and %d is %d", a,b, a+b);
break;
case '-': printf("The subtraction of %d and %d is %d", a,b, a-b);
break;
case '*': printf("The product of %d and %d is %d", a,b, a*b);
break;
case '/': printf("The division of %d and %d is %d", a,b, a/b);
break;
default: printf("Enter the right operator noob!");
}
return 0;
}
scanf(" %s", &sign);
this is not correct. sign is char so it can only store 1 character, but you are trying to read a string which would need more than 1 characters so that would override the memory.
Rather use
scanf(" %c", &sign);
This is a basic question. You should keep in mind that a char can contain a single character from the keyboard. On the other hand, when you do character variable input or output, you should use %c for this purpose. On the other hand, we know, a string is built with multiple character combination. String variable is declared with char
variable[size];
And for string input or output, you need to use %s. As you used no 'string' here, you need to replace %s with %c and that should solve your issue!
Related
I am trying build a simple calculator. But whenever I input both the numbers, it skips straight to the default case and doesn't take in the input of operator. Here is my code -:
#include <stdio.h>
int main()
{
float num1, num2, result;
char opr;
printf("Enter the first number : ");
scanf(" %f ", &num1);
printf("\nEnter the second number : ");
scanf(" %f ", &num2);
printf("\nEnter the operation to be performed (+, -, *, /) : ");
scanf(" %c ", &opr);
switch (opr)
{
case '+' :
result = num1 + num2;
break;
case '-' :
result = num1 - num2;
break;
case '*' :
result = num1 * num2;
break;
case '/' :
result = num1/num2;
break;
default :
printf("\nWrong input.");
break;
}
printf("\nThe result is : %f", result);
return 0;
}
I tried to take the operator input twice and even left a space before "%c" so that it doesn't take newline as input. It skips straight to "Wrong input." section. Any help would be great.
Thank You.
The solution (as provided by Some programmer dude in comments here) is:
don't have trailing (or for almost all formats, leading) spaces in a scanf
Your comments indicate that you aready tried and verified that solution,
but have trouble understanding why it helps.
For visualisation, I modified your code without applying the solution, but with adding some helpful output.
#include <stdio.h>
int main()
{
float num1, num2, result;
char opr;
printf("Enter the first number : ");
scanf(" %f ", &num1);
printf("Got %f.\n", num1);
printf("\nEnter the second number : ");
scanf(" %f ", &num2);
printf("Got %f.\n", num2);
printf("\nEnter the operation to be performed (+, -, *, /) : ");
scanf(" %c ", &opr);
printf("Got %c.\n", opr);
switch (opr)
{
case '+' :
result = num1 + num2;
break;
case '-' :
result = num1 - num2;
break;
case '*' :
result = num1 * num2;
break;
case '/' :
result = num1/num2;
break;
default :
printf("\nWrong input.");
break;
}
printf("\nThe result is : %f", result);
return 0;
}
Try that code with the following input:
1.1<return>
1.2<return>
+<return>
*<return>
And you get the output (with input inbetween):
Enter the first number : 1.1
1.2
Got 1.100000.
Enter the second number : +
Got 1.200000.
Enter the operation to be performed (+, -, *, /) : *
Got +.
The result is : 2.300000
This is because:
1.1 gets scanned into num1, but not before a white space and a non-whitespace is found in input. This only happens with the first <return> and the first part of the second number 1.2. So you have to already enter the second number to make the first scanning work, because of the trailing whitespace in its format string. You have to do that before the prompt for the second number, because the prompt only gets to output after the fist scanning is done.
1.2 gets scanned into num2, but with the same problem, this time satisfied by the second <return> and the operator +. So you have to enter the operator before being prompted to.
+ gets scanned into opr, again with the same problem. It is already need before being prompted for, in order to satisfy the second scanning. It is not yet scanned, it just stops the scanning for a non-whitespace.
Then the prompt for the operator is in output, but at that point it was already required in input, though not being scanned yet.
Then the operator gets scanned into opr, but only if it is again followed by whitespace (the third <return>) and some non-whitespace (the *).
You can see that your program otherwise does as you programmed, yielding 1.1+1.2 being 2.3.
I've been trying to make this if work I've tried to put scanf in every way possible and that was not the problem because it picks it up the "+" is stored as I see it on the printf below.
Can anyone figure out why not?
Thanks
float number1;
float number2;
float total;
char operator[1];
printf("Welcome to the calculator\n");
while(3>2)
{
printf("Pick a number\n");
scanf("%f", &number1);
printf("Que quieres hacer?\n");
scanf(" %c", &operator);
printf("You wrote %s\n", operator);
if(operator =='+')
{
printf("This works!");
}
}
This code snippet
scanf(" %c", &operator);
printf("You wrote %s\n", operator);
if(operator =='+')
{
printf("This works!");
}
is incorrect independent on how the variable operator is declared.
If the variable operator is declared like
char operator;
then this statement
printf("You wrote %s\n", operator);
invokes undefined behavior.
In this case you need to write
printf("You wrote %c\n", operator);
If the variable operator is declared as a character array as for example
char operator[N];
where N is some value then at least this statement
if(operator =='+')
does not make a sense and the condition will always evaluate to false.
Pay attention to that instead of this condition in the while loop
while(3>2)
it would be much simpler and readable just to write
while ( 1 )
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 3 years ago.
In this C program, if I use fflush(stdin) before the second scanf, then it's working fine. And also scanning the operator before the operands, then it's working. I don't understand, why it's working like that.
#include<stdio.h>
int main() {
int a,b,c;
char d;
printf("Enter two operands:");
scanf("%d%d",&a,&b);
printf("\nEnter the operation you desire to perform on Calculator and i.e +, -, *, / :\n");
fflush(stdin);
scanf("%c",&d);
switch(d) {
case '+': printf("\n%d %c %d =%d",a,d,b,(a+b));
break;
case '-': printf("\n%d %c %d =%d",a,d,b,(a-b));
break;
case '*': printf("\n%d %c %d =%d",a,d,b,(a*b));
break;
case '/': (a>b)?(printf("\n%d %c %d =%d",a,d,b,(a/b))):(printf("\n%d %c %d =%d",a,d,b,(b/a)));
break;
default: printf("\nInvalid input");
}
return 0;
}
Output:
Just modify your code to this :
#include<stdio.h>
int main() {
int a,b,c;
char d;
printf("Enter two operands:");
scanf("%d%d",&a,&b);
printf("\nEnter the operation you desire to perform on Calculator and i.e +, -, *, / :\n");
// try give a space like " %c"
scanf(" %c",&d);
switch(d) {
case '+': printf("\n%d %c %d =%d",a,d,b,(a+b));
break;
case '-': printf("\n%d %c %d =%d",a,d,b,(a-b));
break;
case '*': printf("\n%d %c %d =%d",a,d,b,(a*b));
break;
case '/': (a>b)?(printf("\n%d %c %d =%d",a,d,b,(a/b))):(printf("\n%d %c %d =%d",a,d,b,(b/a)));
break;
default: printf("\nInvalid input");
}
return 0;
}
It is working fine :)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This program simulates a simple menu driven calculator with +, -, *, and / operations
#include <stdio.h>
#include <conio.h>
int main()
{
float a = 0, b = 0;
printf(" Enter two numbers: ");
scanf(" %f %f",&a ,&b);
puts(" Enter choice number of operation: ");
puts(" 1)Addition ");
puts(" 2)Subtraction ");
puts(" 3)Multiplication ");
puts(" 4)Division ");
flushall(); //To clear the trailing '\n'
switch( getchar() - 48 )
{
case 1: printf("The Sum of %.2f and %.2f is : %.2f",a,b,(a+b));
break;
case 2: printf("The Difference of %.2f and %.2f is : %.2f",a,b,(a-b));
break;
case 3: printf("The Product of %.2f and %.2f is : %.2f",a,b,(a*b));
break;
case 4: if ( b != 0 ) printf("The Quotient of %.2f and %.2f is : %.2f",a,b,(a/b));
else puts("Error, divide by zero not possible.");
break;
default: puts("Error, Invalid choice");
}
return 0;
}
Is it better this way? As I have avoided the usage of a variable, and equivalently described why the program crashes when the last input is not a valid choice, I don't think there is any need to add info about what was entered. It adds an extra variable into the picture.
Yes, switch statement can take an expression for the value on which you switch. Your code should work fine, except that getchar() would read the leftover '\n' character from scanf of the operands.
Add another call to getchar() before the switch to read and discard that extra character.
While the code is valid and correct, I'd do the following to make it more readable:
switch(getchar()) {
case '1': // ...
case '2': // ...
case '3': // ...
case '4': // ...
}
Or
switch(getchar() - '0') {
case 1: // ...
case 2: // ...
}
This is to avoid using the magic number 48, which may not be understood easily by readers.
Furthermore, you can discard input until the next \n using a simple while loop:
while(getchar() != '\n') ;
In addition to the \n, this will also read and discard anything before the newline.
switch ( expression )
So you have a valid expression and you can have a expression like you have if you really have a need for something like this.
Else
char ch = getchar(); /* or scanf(" %c",&ch); (Better)*/
int a = ch - '0';
switch(a)
{
}
For your answer : Yes the switch can accept an expression in its arguments but it should returns only one of these types char int short long int long long int it can be also signed or unsigned !
There is no need to make a cast for the expression getchar() - 48 because getchar() returns int and 48 is an int so th result would be an int
now after compiling you have to add 3 number one for the variable a and the second for the variable b and the third for the switch statement... for instance
$./executable_file
Enter two numbers: 1 2 3
Switch formatting
This is a suggested formatting of your switch statement. I disagree with the idea of using getchar() in the switch statement (though it is technically legal, it is simply a bad idea in practice), so I've replaced that with c:
int c;
/* c is set by some input operation.
** It might be char c; if you read its value with scanf(), but it must be int if you use getchar()
*/
switch (c)
{
case 1:
printf("The Sum of %.2f and %.2f is : %.2f", a, b, (a+b));
break;
case 2:
printf("The Difference of %.2f and %.2f is : %.2f", a, b, (a-b));
break;
case 3:
printf("The Product of %.2f and %.2f is : %.2f", a, b, (a*b));
break;
case 4:
if (b != 0)
printf("The Quotient of %.2f and %.2f is : %.2f",a, b, (a/b));
else
fputs("Error, divide by zero not possible.\n", stderr);
break;
default:
fprintf(stderr, "Error, Invalid choice %c\n", c);
break;
}
Note the use of break; after the default: label too; it protects you against future additions to the code and is completely uniform. (The default: label does not have to be last, though that is the conventional place for it to go.) Commas get a space after them; so do if, for, while, switch, but function calls do not get a space between the name and the open parenthesis. You don't normally need a space after an open parenthesis or before a close parenthesis. Errors are reported to standard error.
Personally, I like the actions of the switch to be indented just one level, not two levels, so I'd use:
switch (c)
{
case 1:
printf("The Sum of %.2f and %.2f is : %.2f", a, b, (a+b));
break;
case 2:
printf("The Difference of %.2f and %.2f is : %.2f", a, b, (a-b));
break;
case 3:
printf("The Product of %.2f and %.2f is : %.2f", a, b, (a*b));
break;
case 4:
if (b != 0)
printf("The Quotient of %.2f and %.2f is : %.2f",a, b, (a/b));
else
fputs("Error, divide by zero not possible.\n", stderr);
break;
default:
fprintf(stderr, "Error, Invalid choice %c\n", c);
break;
}
Many people disagree, so you're certainly not under an obligation to do that.
I am learning the switch statement of C. This is my small program and it runs and does the calculation but doesn't let me see the result of the operation. The black window shows up so that I input the numbers and the operator and then for a fraction of a second shows the result and disappears. Any help is appreciated.
#include <stdio.h>
int main(int argc, char *argv[])
{
int num1, num2, ans=0;
char ch, name;
printf("Enter a value: ");
scanf("%d", &num1);
printf("Enter a second value: ");
scanf("%d", &num2);
printf("Input * To multiply\
+ To add\
- To subtract: ");
scanf(" %c", &ch);
switch(ch)
{
case'*':
ans=num1 * num2;
printf("%d times %i equals: %i",num1,num2,ans);
break;
case'+':
ans=num1+num2;
printf("%i plus %i equals: %d",num1,num2,ans);
break;
case'-':
ans=num1-num2;
printf("%d minus %d equals: %d",num1,num2,ans);
break;
default:
printf("Range numbers");
}
getchar();
return ch;
}
Probably due to output buffering. Add newlines (\n) last in your formatting strings.
As a newbie, you should end all your printf format string with an escaped newline \n, i.e. printf("%i plus %i equals %d\n", num1, num2, ans); (or you should call fflush(stdout); just after the end of the switch before the getch and before all your scanf).