Switch small program does not let me see result - c

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).

Related

Why the unexpected behaviour for scanf(" %f "... " %f "..." %c ")?

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.

scanf fails when I type in operations (+,-,*,/ etc) in C

I am working on building a calculator in C, and have encountered a problem regarding scanf for characters. I have defined a "string" called operationValue, but when I try to do the scanf function (the one that I have a comment right next to it), it immediately prints out an invalid character instead of the operation I typed in. I needed the string instead of just a character because I have the other operation for powers and roots, but even they don't work when I type them in. When I complete the code it prints "Not Valid Operation."
Sorry if this is not what is conventional in stack overflow, but this is the first time I'm on here. If the pieces of code are too long or something, please help me edit it so I can learn not to do that next time.
#include <stdio.h>
void theOperation(double num1, char operationValue, double num2)
{
if(operationValue == "+")
{
printf("%lf\n", num1 + num2);
} else if(operationValue == "-")
{
printf("%lf\n", num1 - num2);
} else if(operationValue == "*")
{
printf("%lf\n", num1 * num2);
} else if(operationValue == "/")
{
printf("%lf\n", num1 / num2);
} else if(operationValue == "pow")
{
printf("%lf\n", pow(num1, num2));
} else if(operationValue == "root")
{
printf("%lf\n", pow(num1, (1/num2)));
} else
{
printf("Not valid operation");
}
}
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %s", &operationValue);
printf("%c\n", operationValue); // This line fails when I type in any operation I define: '+', '-', '*', '/' 'pow' 'root'
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
Use the "%s" for reading and printing the operator:
#include <stdio.h>
#include <math.h>
#include <string.h>
void theOperation(double num1, char* operationValue, double num2)
{
if(strcmp(operationValue, "+") == 0)
{
printf("%lf\n", num1 + num2);
} else if(strcmp(operationValue, "-") == 0)
{
printf("%lf\n", num1 - num2);
} else if(strcmp(operationValue,"*") == 0)
{
printf("%lf\n", num1 * num2);
} else if(strcmp(operationValue,"/") == 0)
{
printf("%lf\n", num1 / num2);
} else if(strcmp(operationValue,"pow") == 0)
{
printf("%lf\n", pow(num1, num2));
} else if(strcmp(operationValue, "root") == 0)
{
printf("%lf\n", pow(num1, (1/num2)));
} else
{
printf("Not valid operation");
}
}
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %9s", &operationValue);
printf("%c\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
Scanf() docs: https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm
-- EDIT --
I have updated the code to a working one.
I also updated the scanf() for reading the operator like #M. Nejat Aydin commented for prevent buffer overrun
The code has several defects:
The function signature given:
int theOperation(num1, operationValue, num2)
is incorrect. You must define the datatype alongside the identifier.
The function returns int but nowhere used.
A variable char[10] passed into a function which accepts char, which will obviously give unexpected results.
If you want to use mathematical functions like pow(), sqrt(), floor(), etc., you must define the header file math.h. They're not available in stdio.h (that only contains I/O operation functions and subroutines).
Code redefined:
#include <stdio.h>
// return type set to: void, datatypes defined for function parameters
void theOperation(double num1, char operationValue, double num2)
{
double result = 0;
// calculating the results based on operations
switch (operationValue) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
default:
printf("No such operation found.\n");
break;
}
printf("Result: %lf\n", result);
}
int main(void)
{
double num1, num2;
char operationValue;
printf("This is a calculator.\n");
printf("Enter first and second number: ");
scanf("%lf %lf", &num1, &num2);
printf("%lf %lf\n", num1, num2);
printf("Enter operation: ");
scanf(" %c", &operationValue);
printf("%c\n", operationValue);
// the operation execution
theOperation(num1, operationValue, num2);
return 0;
}
The explanation is pretty much simple.
The scanf() takes the necessary data from the user and then passes the parameters to the function theOperation() with their appropriate arguments. Thereafter, the switch statements tries to match which expression is given in case statements are identical to the operationValue.
When it does finds one, it simply evaluates the expression and prints the result.
Note: If you just want to compare single letters like +, -, *, /, etc. then you still don't need to use character array to compare them using strcmp() or anything.
It gives the following output:
This is a calculator.
Enter first and second number: 10 50
10.000000 50.000000
Enter operation: -
-
Result: -40.000000
%c in scanf() is for reading one character. You should use %(max length)s to read strings (that don't contain whitespace characters). The (max length) should be buffer size minus one (for terminating null-character). Also note that %(max length)s will take char*, so you shouldn't put & before arrays.
%c in printf() is for printing one character. You should use %s to print strings.
#include <stdio.h>
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %9s", operationValue);
printf("%s\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
return 0;
}
It wasn't too hard to fix your code by adding types and ensuring the arguments get passed through correctly:
#include <stdio.h>
#include <stdlib.h>
void theOperation(double num1, char operationValue, double num2)
{
switch (operationValue) {
case '+':
printf("%lf\n", num1 + num2);
break;
case '-':
printf("%lf\n", num1 - num2);
break;
case '/':
printf("%lf\n", num1 / num2);
break;
case '*':
printf("%lf\n", num1 * num2);
break;
default:
printf("Not valid operation");
}
}
int main()
{
double num1, num2;
char operationValue;
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf(" %c", &operationValue);
printf("%c\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
I made fixes in function parameters, strings vs. chars and wrong scanf format chars, taking all your operations including "pow" and "root" and combining it with switch():
#include <stdio.h>
#include <math.h>
#include <string.h>
void theOperation(double num1, const char *operationValue, double num2)
{
switch(*operationValue) {
case '+': printf("%lf\n", num1 + num2); break;
case '-': printf("%lf\n", num1 - num2); break;
case '*': printf("%lf\n", num1 * num2); break;
case '/': printf("%lf\n", num1 / num2); break;
default: {
if(!strcmp(operationValue, "pow")) {
printf("%lf\n", pow(num1, num2));
} else if(!strcmp(operationValue, "root")) {
printf("%lf\n", pow(num1, (1/num2)));
} else printf("Not valid operation\n");
break;
}
}
}
int main()
{
double num1, num2;
char operationValue[10];
printf("This is a calculator.\n");
printf("Enter first number: ");
scanf("%lf", &num1);
printf("%lf\n", num1);
printf("Enter operation: ");
scanf("%9s", operationValue);
printf("operation entered: %s\n", operationValue);
printf("Enter second number: ");
scanf("%lf", &num2);
printf("%lf\n", num2);
theOperation(num1, operationValue, num2);
return 0;
}
Output example with "power":
$ gcc -Wall -o calc calc.c ;./calc
This is a calculator.
Enter first number: 2
2.000000
Enter operation: pow
operation entered: pow
Enter second number: 3
3.000000
8.000000
This is an important line:
scanf("%9s", operationValue);
(Read a string with up to 9 chars.)

Catching the user entering a string when expecting an integer?

I am making a program where the user enters two binary numbers and an operation character then I print the output in decimal. I want the while loop to keep the program running until the user enters quit. How can I read if the user enters quit and not an integer value in the scanf? Is there a way to catch this?
#include <stdio.h>
#include <string.h>
int toDecimal(int num);
int main(){
// Define variables
int num1, num2, result = 0;
char op;
char run[4] = "go";
// While loop to rerun program until quit is entered
while(strcmp(run, "quit\n") != 0){
// Reads user input
scanf("%i %c %i", run, &num1, &op, &num2);
printf("\nnum1: %i num2: %i op: %c\n", num1, num2, op);
num1 = toDecimal(num1);
num2 = toDecimal(num2);
printf("\nnum1: %i num2: %i op: %c\n", num1, num2, op);
}
printf("\nGoodbye!\n");
return 0;
}
I believe that I may be able to read everything in as a string and then convert to an integer however I don't know how. Is this a solution I should look into?
How can I read if the user enters quit and not an integer value in the scanf?
There is no good way with scanf(). Instead get user input with fgets() and do not use scanf() until you know why it is bad.
// Read user input
char buf[80]; // Use adequate size input buffer,
while (fgets(buf, sizeof buf, stdin)) {
buf[strcspn(buf, "\n")] = '\0'; // Lop off potential trailing \n
if (sscanf(bufm "%i %c %i", &num1, &op, &num2) == 3) {
printf("\nnum1: %i num2: %i op: %c\n", num1, num2, op);
num1 = toDecimal(num1);
num2 = toDecimal(num2);
printf("\nnum1: %i num2: %i op: %c\n", num1, num2, op);
} else if (strcmp(buf, "quit")== 0) {
break;
} else {
printf("Bad input <%s> ignored\n", buf);
}
}
This is a pretty basic idea , I hope you get the point.You could also use dynamic memory allocation when reading the string.
Basically you read the whole input with fgets and you extract the variables using sscanf.
#include <stdio.h>
#include <string.h>
int main ()
{
int n1,n2;
char arr[1000],oper;
fgets(arr,sizeof(arr),stdin);
while (strcmp(arr,"quit\n")!=0){
if (sscanf(arr,"%d %c %d",&n1,&oper,&n2)==3); /* Scanning for each number and operator and checking input*/
else
printf("wrong input");
/* Code */
fgets(arr,sizeof(arr),stdin);
}
return 0;
}

Can somebody tell me why I have this runtime error?

I have created a program on Pelles C, however, when I run it, it is skipping straight to the end of the function simply saying "press any key to continue"
#include <stdio.h>
int main()
{
char letter;
int num1, num2;
printf("Enter any one keyboard character ");
scanf("%c", &letter);
printf("Enter 2 integers seperated by a space ");
scanf("%d %d", &num1, &num2);
printf("Numbers inputted were %d and %d \n" num1, num2);
printf("letter input %c", letter);
printf(" Stored at: %p \n", &letter);
return 0;
}
Can anybody tell me why this is happening ?
printf("Numbers inputted were %d and %d \n" num1, num2);
^
You missed a , before num1 in above printf statement.
printf("Numbers inputted were %d and %d \n",num1, num2);

how to repeat a c program from the beginning and clean the screen and 1st input values?

i m new in programing.
i've written a simple program.
i want to repeat the program again and again and it can only exit when user wants to exit.
here is my program
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
int num1, num2, a, m, s, choice;
float d;
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Any Key To Exit");
getch();
return 0;
}
and here is the output
"Enter The First Number: 10
Enter The Second Number: 10
Enter Your Choice
For Addition Type A
For Multipication Type M
For Division Type D
For Substraction Type S : A
The Addition Of The Number Is= 20
Press Any Key To Exit"
I want a line before the line Press Any Key To Exit
"If You Want To Calculate Again Press Y
or
Press Any Key To Exit"
when press Y then the program should start from the beginning.
How can i do this???
wrap the code inside a do{} while() ?
char answer;
do{
printf("\nEnter The First Number: ");
scanf("%d", &num1);
printf("\nEnter The Second Number: ");
scanf("%d", &num2);
a=num1+num2;
m=num1*num2;
s=num1-num2;
d=(float)(num1/num2);
printf("\nEnter Your Choice \nFor Addition Type A \nFor Multipication Type M \nFor Division Type D \nFor Substraction Type S : ");
scanf(" %c", &ch);
switch(ch)
{
case 'A': printf("\nThe Addition Of The Number Is= %d", a);
break;
case 'M': printf("\nThe Multipication Of The Numbers Is= %d", m);
break;
case 'S': printf("\nThe Substraction Of THe Numbers Is= %d", s);
break;
case 'D': printf("\nThe Division Of The Two Numbers Is= %f", d);
break;
default : printf("\nInvalid Entry");
break;
}
printf("\nPress Y to continue. Press any Key To Exit");
scanf(" %c",&answer); // dont forget type &
}
while(answer == 'y' || answer == 'Y');
Declare a variable, let's say answer, which will store the user answer when you ask for "Press Y to continue. Press any Key To Exit". Check to see what value has that variable. If is 'y' or 'Y', the loop will repeat. If the user pressed other key, the loop is over.
You can also use recursion, which is often used in more functional oriented programming languages.
Pseudo-code:
myfunction = do
...
b <- somethingtodo
...
if b
then myfunction
else return ()
Relative to Jens's solution, it would look like:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
char choice;
int num1, num2, cont;
printf("Enter the first number: ");
scanf("%d", &num1);
getchar ();
printf("Enter the second number: ");
scanf("%d", &num2);
getchar ();
printf("A - addition\n");
printf("S - subtraction\n");
printf("M - multiplication\n");
printf("D - division\n");
printf("[ASMD]? ");
choice = (char)toupper(getchar());
getchar ();
printf("\n");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
printf("Continue [YN]? ");
cont = toupper(getchar());
getchar ();
if (cont == 'Y')
return main(); // the difference.
else if (cont == 'N')
return EXIT_SUCCESS;
}
}
I would move the calculation stuff in it's own function and then use while() in main.
I have tried to fix other problems as well (this solution only uses standard C functions).
#include <stdio.h> // puts, printf, fprintf, scanf, getchar, stderr, EOF
#include <stdlib.h> // exit, EXIT_SUCCESS, EXIT_FAILURE
#include <ctype.h> // toupper
char fail_on_eof (int c)
{
if (c == EOF)
exit (EXIT_FAILURE);
// In case of fail_on_eof (scanf (...)) the return value of this this
// function is not useful
// scanf () returns the number of chars read or EOF
// getchar () returns a char or EOF
return (char) c;
}
void skip_to_next_line (void)
{
char c;
do
{
c = fail_on_eof (getchar ());
} while (c != '\n');
}
char read_upcase_char_line (char* prompt)
{
char c;
printf ("%s ", prompt);
c = fail_on_eof (toupper (getchar ()));
skip_to_next_line ();
return c;
}
int read_num_line (char* prompt)
{
int num;
printf ("%s ", prompt);
fail_on_eof (scanf ("%d", &num));
skip_to_next_line ();
return num;
}
int calculate (void)
{
char choice;
int num1, num2, cont;
num1 = read_num_line ("Enter the first number:");
num2 = read_num_line ("Enter the second number:");
puts("A - addition");
puts("S - subtraction");
puts("M - multiplication");
puts("D - division");
choice = read_upcase_char_line ("[ASMD]?");
puts("");
switch(choice)
{
case 'A':
printf("%d + %d = %d", num1, num2, num1 + num2);
break;
case 'S':
printf("%d - %d = %d", num1, num2, num1 - num2);
break;
case 'M':
printf("%d * %d = %d", num1, num2, num1 * num2);
break;
case 'D':
if (num2 == 0)
// Better use stderr for error messages
fprintf(stderr, "The divisor can not be zero");
else
{
printf("%d / %d = %f", num1, num2, (double)num1 / num2);
}
break;
default :
// Better use stderr for error messages
fprintf(stderr, "Invalid entry");
break;
}
printf("\n");
for (;;)
{
cont = read_upcase_char_line ("Continue [YN]?");
if (cont == 'Y')
return -1;
else if (cont == 'N')
return 0;
}
}
int main(void)
{
while (calculate ());
return EXIT_SUCCESS; // Use this constant to avoid platform specific issues with the return code
}

Resources