I’m trying to get user input and allowing them to only input a whole number which is also positive.
I’m trying to figure out this task
printf("Enter the first and second number in whole number: ");
scanf("%d,%d", &first, &second);
if (input != '\n') //notice this line I'm trying to check if is a character//
printf("Error! CHARACTER NOT ACCEPTED!!\n");
else if (First <= 0)
printf("Error! First must be a positive value!\n");
else if (Second <= 0)
printf("Error Second must be a positive value!\n");
The code above will check for two things. One, if the user has input the characters I want. Second, if the number is positive.
How do I realize these checks?
You cannot restrict the characters the user inputs. You should read whatever the user gives you and decide what to do with it.
If you want to use scanf, it could be like this:
scanf‘s return value shows the number of%s it successfully read. For example:In the last example,
xfwill stay in input and furtherscanfs would read it.So for the first
if, you simply check if the return value ofscanfis 1. If not, then you couldn’t read a number from input.For the second
if, check ifnum <= 0