I am creating a calculator file in C with a while loop and a switch statement. The first time through the while loop, everything works fine, but when it goes through the second time, the my printf gets called before I have the opportunity to enter the data into the preceding scanf.
I have tried using '\n' before the text in the printf and I have also tried using fflush(stdout) before and after the scanf call.
Current output:
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: A
Enter both numbers in required sequence: 50 50
// the output of the calculator does <>= 100 // Equal to 100.
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: Enter both numbers in required sequence:
What I want:
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: A
Enter both numbers in required sequence: 50 50
// the output of the calculator does <>= 100 // Equal to 100.
Welcome to the Calculator
Operation choices: Addition(A)
Subtraction(S)
Multiplication(M)
Division(D).
Enter choice: // then I can enter a new choice for the switch //
The code I've tried:
while(input != 'q'){
printf("Welcome to the Calculator\nOperation choices:\tAddition(A)\n\t\t\tSubtraction(S)\n\t\t\tMultiplication(M)\n\t\t\tDivision(D)\nEnter choice: ");
fflush(stdout);
scanf("%c", &input);
fflush(stdout);
printf("\nEnter both numbers in required sequence: ");
scanf("%f %f", &num1, &num2);
switch(input){
case 'A':
result = num1 + num2;
break;
case 'S':
result = num1 - num2;
break;
case 'M':
result = num1 * num2;
break;
case 'D':
result = num1 / num2;
break;
default:
printf("Please choose a valid operation.");
break;
}
if(result > 100){
printf("Greater than 100.\n");
}
else if(result < 100) {
printf("Less than 100.\n");
}
else{
printf("Equal to 100.\n");
}
}
printf("Quit the menu.\n");
return(0);
}
The sequence of events in you program is correct, what happens is that scanf() reads a lingering '\n' new line character that is left in the stdin buffer from a previous input. The '\n' is consumed by scanf() and the program continues the execution.
You will need to clear the buffer before scanf() is executed.
Option 1 - Clear the buffer at the bottom of the while cycle:
//...
int c;
//...
else{
printf("Equal to 100.\n");
}
while((c = fgetc(stdin)) != '\n' && c != EOF){}
//...
Option 2 (simpler) - Use a space before %c specifier:
scanf(" %c", &input);
^
Try this : scanf(" %c", &input); (add space before %c)
scanf will likely take \n in buffer as input and placed in you character input.
good evening,
Here is my code. I am making a little calculator but I'm battling at the end to make the function repeat with a y/n loop. I have looked at others but can't seem to get the right answer.
Thanks.
#include <stdio.h>
int main()
{
int n, num1, num2, result;
char answer;
{
printf("\nWhat operation do you want to perform?\n");
printf("Press 1 for addition.\n");
printf("Press 2 for subtraction.\n");
printf("Press 3 for multiplication.\n");
printf("Press 4 for division.\n");
scanf("%d", &n);
printf("Please enter a number.\n");
scanf("%d", &num1);
printf("Please enter the second number.\n");
scanf("%d", &num2);
switch(n)
{
case 1: result = num1 + num2;
printf("The addition of the two numbers is %d\n", result );
break;
case 2: result = num1 - num2;
printf("The subtraction of the two numbers is %d\n", result );
break;
case 3: result = num1 * num2;
printf("The multiplication of the two numbers is %d\n", result );
break;
case 4: result = num1 / num2;
printf("The division of the two numbers is %d\n", result );
break;
default: printf("Wrong input!!!");
}
printf("\nDo you want to continue, y/n?\n");
scanf("%c", &answer);
while(answer == 'y');
}
return 0;
}
You have this code
char answer;
{
printf("\nWhat operation do you want to perform?\n");
//...
//... more code
//...
printf("\nDo you want to continue, y/n?\n");
scanf("%c", &answer);
while(answer == 'y');
}
Try to change it to:
char answer;
do {
printf("\nWhat operation do you want to perform?\n");
//...
//... more code
//...
printf("\nDo you want to continue, y/n?\n");
scanf("%c", &answer);
} while(answer == 'y');
So the basic form is:
do {
// code to repeat
} while (Boolean-expression);
BTW - You should always check the value returned by scanf
Example:
if (scanf("%c", &answer) != 1)
{
// Add error handling
}
Also notice that you often want a space before %c to remove any white space (including newlines) in the input stream. Like
if (scanf(" %c", &answer) != 1)
{
// Add error handling
}
This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 5 years ago.
There are two different spots where the check happens.
That is, where you enter a, s, m, d, or q and when you enter the first and second number.
At any of the checks, if the check is false, it should ask you to re-enter your input.
I'm guessing this can be done by putting a scanf statement for the numbers part inside a while loop check, but when I enter an invalid value (non-number) the loop runs infinitely.
So I must be doing something wrong. I have made the a, s, m, d, and q part work for the most part.
But the second part never seems to work. For this, I left my failed attempts at the while loops out, and instead in //comments.
Any help would be greatly appreciated!
Here is my code so far:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
float num1,num2,answer;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
while ((ch = getchar())!='q')
{
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
ch=tolower(ch);
if (ch=='\n')
continue;
else
{
switch(ch)
{
case 'a':
//The code below is what I have tried to make work.
//This code would also be copy pasted to the other cases,
//of course with the correct operations respectively being used.
//
//printf("Enter first number: ")
//while(scanf("%f",&num1)==0)
//{
// printf("Invalid input. Please enter a number.");
// scanf("%f",&num1);
//}
//printf("Enter second number: ")
//while(scanf("%f",&num2)==0)
//{
// printf("Invalid input. Please enter a number.");
// scanf("%f",&num2);
//}
//answer = num1 + num2;
//printf("%f + %f = %f\n",num1,num2,answer);
//break;
//
//I have also tried to make this work using do-while loops
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 + num2;
printf("%f + %f = %f\n",num1,num2,answer);
break;
case 's':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 - num2;
printf("%f - %f = %f\n",num1,num2,answer);
break;
case 'm':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 * num2;
printf("%f * %f = %f\n",num1,num2,answer);
break;
case 'd':
printf("Enter first number: ");
scanf("%f",&num1);
printf("Enter second number: ");
scanf("%f",&num2);
answer = num1 / num2;
printf("%f / %f = %f\n",num1,num2,answer);
break;
default:
printf("That is not a valid operation.\n");
break;
}
}
}
return 0;
}
Again, thanks for any help!
Ya'll would be a life saver!
Cheers!
-Will S.
EDIT: I got my code to work! Here is the final code...
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
float num1,num2,answer;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
while ((ch = getchar())!='q')
{
ch=tolower(ch);
//Ignore whitespace
if (ch=='\n')
continue;
else
{
switch(ch)
{
//Addition part
case 'a':
//First number
printf("Enter first number: ");
//Check to see if input is a number
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Second number
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Do math for respective operation
answer = num1 + num2;
//Print out result
printf("%.3f + %.3f = %.3f\n", num1,num2,answer);
break;
//Subtraction part
case 's':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
answer = num1 - num2;
printf("%.3f - %.3f = %.3f\n", num1,num2,answer);
break;
//Multiplication part
case 'm':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
answer = num1 * num2;
printf("%.3f * %.3f = %.3f\n", num1,num2,answer);
break;
//Division part
case 'd':
printf("Enter first number: ");
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
printf("Enter second number: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
//Check for if number is a zero
while (num2==0)
{
printf("Please enter a non-zero number, such as 2.5, -1.78E8, or 3: ");
while (scanf("%f",&num2)==0)
{
printf("Invalid input. Please enter a number, such as 2.5, -1.78E8, or 3: ");
scanf("%*s");
}
}
answer = num1 / num2;
printf("%.3f / %.3f = %.3f\n", num1,num2,answer);
break;
//For if a non-valid operation is entered
default:
printf("That is not a valid operation.\n");
break;
}
}
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply q. divide\n");
printf("q. quit\n");
}
printf("Bye.\n");
return 0;
}
Looking back at it, I probably could do without the if/else statement.
There are multiple problems with your code. First of all in this loop
You are taking input two times on failure
while(scanf("%f",&num1)==0) //Taking Input Here Once
{
printf("Invalid input. Please enter a number.");
scanf("%f",&num1); //Again Taking input.
}
Instead what you wanted was to check the return value of the scanf() and if it was 0 you would execute the loop again, so this would be the way to do that:
int l = 0;
while(l==0){ //Checking l, if it is zero or not, if zero running loop again.
printf("Invalid input. Please enter a number.");
l = scanf("%f",&num1); //Storing Return Value of scanf in l
}
When the program will encounter any line with scanf("%f" , &num1) or scanf("%f" , &num2), it will skip all the white spaces and wait for next input. In the case where the input does not match the format specification, then the input isn't consumed and remains in the input buffer.
int l = 0;
while(l==0){ //Checking l
printf("Invalid input. Please enter a number.");
l = scanf("%f",&num1); //scanf will look at the buffer if the input
//does not match, it will not be consumed
//and will remain in buffer.
}
In other words, the character that doesn't match is never read. So when you type e.g. an a character, your code will loop indefinitely as scanf continues to fail on the same character.
When the program executes its last scanf("%f",&num2) call then because of the enter there is a newline \n character present in buffer and so due to ch = getchar(), new line \n gets stored in ch and the following if condition satisfies and the loop execute again.
if(ch =='\n')
continue;
while(scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number.");
scanf("%f",&num1);
}
This loops scans two numbers per iteration. This is not what you want. Lose the second scanf.
You should also check for EOF and errors.
int result;
while((result = scanf("%f",&num1))==0)
{
printf("Invalid input. Please enter a number.");
}
if (result == EOF) .... report an error and exit ...
I am writing a program that can calculate the areas of a square, cube, and circle. The program needs to present an error message and allow the user to enter a new choice if they enter something not included in the menu. My problem is that if they type anything includes my menu options then the program still executes. (i.e. -1, 23, 344) I was wondering how to get it to ignore anything after the first character or to read the whole string. Or if there is something better than getchar(). I'm open to any solutions! Thank you!
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int choice;
int lengthsq;
int areasq;
int lengthcube;
int areacube;
int radius;
double circlearea;
printf("Area Calculation\n");
printf("(1) Square\n");
printf("(2) Cube\n");
printf("(3) Circle\n");
fputs("Please make a selction: ", stdout);
while((choice = getchar()) != '\n')
switch (choice) {
case '1':
printf("\nPlease enter the length: ");
scanf("%d", &lengthsq);
while(lengthsq <= 0){
printf("Error! Please enter a positive number: ");
scanf("%d", &lengthsq);
}
areasq = lengthsq * lengthsq;
printf("The area of the square is %d.", areasq);
return 0;
case '2':
printf("\nPlease enter the length: ");
scanf("%d", &lengthcube);
while (lengthcube <= 0) {
printf("Error! Please enter a positive number: ");
scanf("%d", &lengthcube);
}
areacube = 6 * lengthcube * lengthcube;
printf("The surface area of the cube is %d.\n", areacube);
return 0;
case '3':
printf("\nPlease enter the radius: ");
scanf("%d", &radius);
while(radius <= 0){
printf("Error! Pleae enter a postive number: ");
scanf("%d", &radius);
}
circlearea = 3.14159 * radius * radius;
printf("The area of the circle is %.2f.\n", circlearea);
return 0;
case '\n':
case '\t':
case ' ':
break;
default:
printf("\nInvalid choice entered.\n");
fputs("Enter a new choice: ", stdout);
break;
}
}
You could add another switch case for the dash, which would toggle some kind of negative flag and then read a number as you're already doing. If you do not like introducing such a flag, then the best option would be using fgets, which returns the entire input line. But that has the downside that you need to parse the input. I.e. do some string manipulation, which may be slightly more complex than a simple flag parameter.
On the other hand, from the code you attached, I deduct that the only valid input consists of mere numbers (integers). You could just read an integer then with scanf.
I wrote below code:
#include<stdio.h>
int main() {
char o,r;
int x,y;
do {
printf("Enter operator: '+' or '-' or '*' or '/'\n");
scanf("%c",&o);
printf("Enter first number: ");
scanf("%d",&x);
printf("Enter second number: ");
scanf("%d",&y);
switch(o) {
case '+':
printf("Sum: %d",x+y);
break;
case '-':
printf("Subtract: %d",x-y);
break;
case '*':
printf("Multiply: %d",x*y);
break;
case '/':
printf("Division: %d",x/y);
break;
default:
printf("Wrong operator entered.");
}
printf("\nEnter y or Y to continue: ");
scanf("%c",&r); // r is not getting value?. why?
} while((r=='y')||(r=='Y'));
}
r is not getting value thus it is not doing what it supposed to do.
printf("\nEnter y or Y to continue: ");
scanf("%c",&r);
What seems to be the problem? Am I missing something?
Why does this code work fine in c++ if I use cin, but it fails when I use scanf in c?
You need to add the line (or something similar):
while(getchar() != '\n');
After you enter the second number, '\n', the newline character, is left in stdin and is being placed in r.
You can prove this by adding the following lines after the while loop:
if(r == '\n')
printf("\nnewline\n");
Enter operator: '+' or '-' or '*' or '/'
*
Enter first number: 5
Enter second number: 6
Multiply: 30
Enter y or Y to continue:
newline
check the below
#include<stdio.h>
int main()
{
char o,r;
int x,y;
do{
printf("Enter operator: '+' or '-' or '*' or '/'\n");
scanf(" %c",&o);
printf("Enter first number: ");
scanf("%d",&x);
printf("Enter second number: ");
scanf("%d",&y);
switch(o)
{
case '+':
printf("Sum: %d",x+y);
break;
case '-':
printf("Subtract: %d",x-y);
break;
case '*':
printf("Multiply: %d",x*y);
break;
case '/':
printf("Division: %d",x/y);
break;
default:
printf("Wrong operator entered.");
}
printf("\nEnter y or Y to continue: ");
scanf(" %c",&r);
} while((r=='y')||(r=='Y'));
}