I need to ask an input from a user and he/she should have the ability to write a float number, and I need to do some calculation on the 2 numbers, but I’m having a problem after the isdigit test…even if I enter an integer its going to the continue;
This is my code:
#include <stdio.h>
#include <ctype.h>
char get_choice(void);
float calc(float number1, float number2);
int main()
{
float userNum1;
float userNum2;
get_choice();
printf("Please enter a number:\n");
while ((scanf("%f", &userNum1)) == 1)
{
if (!isdigit(userNum1))
{
printf("Please enter a number:\n");
continue;
}
printf("Please enter another number:\n");
while ((scanf("%f", &userNum2) == 1))
{
if (!isdigit(userNum2))
{
printf("Please enter a number:/n");
continue;
}
else if (userNum2 == '0')
{
printf("Please enter a numer higher than 0:\n");
continue;
}
}
}
calc(userNum1, userNum2);
return 0;
}
float calc(float number1, float number2)
{
int answer;
switch (get_choice())
{
case 'a':
answer = number1 + number2;
break;
case 's':
answer = number1 - number2;
break;
case 'm':
answer = number1 * number2;
break;
case 'd':
answer = number1 / number2;
break;
}
return answer;
}
char get_choice(void)
{
int choice;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply d. divide\n");
printf("q. quit\n");
while ((choice = getchar()) == 1 && choice != 'q')
{
if (choice != 'a' || choice != 's' || choice != 'm' || choice != 'd')
{
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply d. divide\n");
printf("q. quit\n");
continue;
}
}
return choice;
}
Apologize for uploading the functions as well, but since I’m a newbie the problem might be there.
Cheers.
isDigit()only takes a character input.The best way to check that you are getting input correctly is to use
Since
scanf()will return the number of items correctly scanned.