r/C_Programming • u/erojerisiz • Jul 04 '26
Question How to loop for wrong input
Just new to C and I'm trying to make a basic calculator. I'm trying to figure out how to make a loop such that the program will run after failing due to incorrect user input. So far, this is what I came up with, and I just want to know how I can get the program to actually run the operations when entering a correct sign after getting a "try again" message.
#include <stdio.h>
float addition(float num1, float num2)
{
return num1 + num2;
}
float subtraction(float num1, float num2)
{
return num1 - num2;
}
float multiplication(float num1, float num2)
{
return num1 * num2;
}
float division(float num1, float num2)
{
return num1 / num2;
}
int main()
{
float firstNum, secondNum;
char operationSign;
float answer;
printf("Basic Calculator\n\n");
printf("Enter the first number: ");
scanf("%f", &firstNum);
printf("Enter the second number: ");
scanf("%f", &secondNum);
printf("Enter the operation symbol to be used:\n");
printf("Addition: +\n");
printf("Subtraction: -\n");
printf("Multiplication: *\n");
printf("Division: /\n");
scanf(" %c", &operationSign);
switch (operationSign)
{
case ('+'):
answer = addition(firstNum, secondNum);
printf("Answer: %f", answer);
break;
case ('-'):
answer = subtraction(firstNum, secondNum);
printf("Answer: %f", answer);
break;
case ('*'):
answer = multiplication(firstNum, secondNum);
printf("Answer: %f", answer);
break;
case ('/'):
answer = division(firstNum, secondNum);
printf("Answer: %f", answer);
break;
default:
printf("Invalid input. Please enter the correct symbol.");
scanf(" %c", &operationSign);
}
return 0;
}
7
Upvotes
1
u/sciencekm Jul 04 '26
You can use a "while(1)" but this generates warning on some compilers. I my prefer a "for(;;)"
My suggestion would be have all the input in one line instead of multiple lines. You loop while there is input. It would be something like:
#include <stdio.h>
void main(void) {
float v1, v2, r;
char s[64], op;
while(fgets(s, 64, stdin) && sscanf(s, "%f %c %f", &v1, &op, &v2) == 3) {
switch(op) {
case '+': r = v1 + v2; break;
case '-': r = v1 - v2; break;
case '*': r = v1 * v2; break;
case '/': r = v1 / v2; break;
default: puts("invalid");
continue;
}
printf("%f\n", r);
}
}
This is obviously an imperfect example to demonstrate the concept.
1
u/Key_River7180 Jul 04 '26
scanf() returns the number of variables written to. If the user didn't provide input or input wasn't a number, scanf will return 0, if it wrote to one variable then 1, make a function like:
2
u/HeywoodJablowmenow Jul 04 '26
Use a while (1) loop
1
u/SmokeMuch7356 Jul 04 '26
Don't use
scanf- it's great when you know your input is always going to be well-behaved, but it is difficult to detect and recover from bad input with it. Instead, read your numeric input as text usingfgets, then convert it todoubleusingstrtod. It takes a parameter that will point to the first character not converted; if that character is anything other than whitespace or a terminator, then the input is invalid.Create separate input routines for both your operator and operands; you'll do the validation and loop on error within those routines.
Here's an example for getting your operands:
Some examples, called as
Do something similar to read your operator, and your logic can be something like
As a rule, you should use
doubleinstead offloatfor your operands. It will give you greater precision, and it's the "default" floating point type; floating-point constants like3.14159are double unless you tack on an f suffix (2.14159f),floatarguments to variadic functions likeprintfwill be "promoted" todouble, etc.1
u/ANixosUser Jul 05 '26
i'd like to help, but it's really hard to read. some things i noticed about the code (unrelated to you issue):
- you dont need the ( and ) in the case statements. this works too:
- you dont have indentation at all. its not necessary, but it makes the code way easier to read. just press tab in front of each line so that the code gets indented (see switch-case for example).
- you have many unnecessary functions. you dont need them for something like a + b, a * b. functions also take a bit of performance away.
just wanted to give some advice :)