I am trying to write a code in C (gcc) to accept only floating numbers and reject integers, special characters, alphanumeric entries.
I want it to see if printf("First number: \n");
& printf("Second number: \n");
are floating numbers with decimals otherwise ask the user to re-enter a floating number since his first input was invalid.
I want that to happen before it starts calculating. I need a code expample if possible
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
float a, b, sm;
int i = 2;
printf("First number: \n");
scanf("%f", &a);
printf("Second number: \n");
scanf("%f", &b);
printf ("%.2f + %.2f = %.2f -> Summe \n", a, b, sm = a+b);
printf ("%.2f / %d = %.2f -> Mittelwert \n", sm, i, sm/i);
printf ("%.2f - %.2f = %.2f -> Differenz \n", a, b, a-b);
printf ("%.2f * %.2f = %.2f -> Produkt \n", a, b, a*b);
printf ("%.2f / %.2f = %.2f -> Division\n", a, b, a/b);
}
Thank you for your time!
The integers will be converted into floating point numbers, i.e. if the number is given 5
then it'll be converted into 5.0
for the floating point variable implicitly. Hence, none should worry about that.
Use the following program:
#include <stdio.h>
float ask_loop(float f) {
int ret = scanf("%f", &f);
float fl = f;
if (ret != 1) { // if scanf() returns error code
printf("Error! Please input numbers correctly.\n");
fflush(stdin);
fl = ask_loop(f);
}
return fl;
}
int main(void)
{
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
float a, b, sm;
int i = 2;
printf("First number: \n");
a = ask_loop(a);
fflush(stdin);
printf("Second number: \n");
b = ask_loop(b);
printf ("%.2f + %.2f = %.2f -> Summe \n", a, b, sm = a+b);
printf("%.2f / %d = %.2f -> Mittelwert \n", sm, i, sm / i);
printf("%.2f - %.2f = %.2f -> Differenz \n", a, b, a - b);
printf("%.2f * %.2f = %.2f -> Produkt \n", a, b, a * b);
printf("%.2f / %.2f = %.2f -> Division\n", a, b, a / b);
}
Here we've used a function ask_loop()
which verifies if the scanf()
doesn't returns an exit code. If it doesn't, it means it has accepted the value successfully, otherwise does recursion again. At the end of the function, it returns the number inputted and assigns to the variable in main()
.
Sample Output:
First number: // --- INPUT
abc
Error! Please input numbers correctly. // --- OUTPUT
2.0
Second number: // --- INPUT
5
2.00 + 5.00 = 7.00 -> Summe // --- OUTPUT
7.00 / 2 = 3.50 -> Mittelwert
2.00 - 5.00 = -3.00 -> Differenz
2.00 * 5.00 = 10.00 -> Produkt
2.00 / 5.00 = 0.40 -> Division (5 -> 5.00)