How to prevent non-integer input in c? [duplicate] - c

This question already has answers here:
How to scanf only integer?
(9 answers)
Closed 1 year ago.
I am trying to run a program whereby user can only enter 1 or 2. If the user enters any other numbers or alphabets, it should prompt the user back to entering input again. I have tried the following code and it works if user enter an integer which is not 1 or 2, but the whole program will go haywire if entered any alphabets. I tried to validate with
if == 0 but doesnt work as well. Does anyone have any idea?
int getUserInput(){
printf("1: You have chosen 1.\n");
printf("2: You have chosen 2.\n\n");
printf("Enter an option: ");
scanf("%d", &userSel);
if(userSel!= 1 && userSel!= 2){
printf("You have entered an invalid input. Please try again.\n");
getUserInput();
}
else{
printf("Enter a number: ");
scanf("%d", &userNo);
}
printf("userSelection: %d\n", userSel);
printf("1userNumber: %d\n", userNo);
return 0;
}

Perhaps you can make it so scanf sets the variable that will hold the user input only when the input is a integer. You can use this stack overflow link here that has a similar question to yours!
How to scanf only integer?

Related

Why scanf scans different number than the one I enter? [duplicate]

This question already has answers here:
"printf" only printing variable addresses
(2 answers)
Closed 3 years ago.
So I'm using C for a few days and I didn't have this problem before but now I have a problem with C scanning different number than the one the user enter. I feel like it prints the location of the number but not the number itself. The number I get every time is 6422076 and if I print another number that I've scan from the user it just show the same number -4, 6422072 so I'm pretty sure It has to do with the location the computer storage the numbers.
I tried to print it with a few other ways and always get the same weird number.
void measures()
{
int height;
printf("\nEnter your height:\n");
scanf("%d",&height);
while(height<140 || height>210){
printf("Invalid input, try again: \n");
scanf("%d",&height);
}
printf("height: %d\n",&height);
}
not getting any errors
Here's your problem:
printf("height: %d\n",&height);
You're not printing the value of height. You're printing its address. Remove the address-of operator:
printf("height: %d\n",height);

C Program Won't End When User Enters Invalid Character [duplicate]

This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 4 years ago.
I'm trying to write a C program that computes X^Y (X to the Y power) without using the 'pow' function. The program works fine when I enter numbers, but I'm having an issue with the code not stopping when the user enters a character that isn't a number. It runs through the program once more after giving the message "The character you have entered is not a number.Please try again.The character you have entered is not a number.Please try again. The value is 1." Can someone help? I'm going insane trying to figure this out.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, y, i,n=1,val;
printf("Please enter a number: \n");
scanf("%d", &x);
if (x!=1)
printf("The character you have entered is not a number.Please try again.");
else
printf("What power is the number raised to?\n");
scanf("%d", &y);
if (y!=1)
printf("The character you have entered is not a number.Please try again.");
else
for(i=1;i<=y;i++)
{
val=x;
n=n*val;
}
printf("The value is %d.\n", n);
return 0;
}
When your program detects invalid input, it prints a message, but otherwise just continues on ahead as if a valid input had been read. Instead, it needs to do one of these things:
abort when invalid input is detected, or
consume and ignore the invalid input, AND
loop back to provide a chance to enter new input, or
use a default value.
Its message suggests that the program will provide for entering new input, but in fact it does not follow through. Moreover, if it is the input for the first prompt that is invalid, then that input is still waiting to be read when the program prints the second prompt, where it is still invalid, and the program blithely continues on a second time, ultimately printing the initial value of n, 1, without having calculated anything.
You need to check how many items scanf successfully read:
int numItemsRead = 0;
printf("What power is the number raised to?\n");
numItemsRead = scanf("%d", &y);
if (numItemsRead!=1)
printf("The character you have entered is not a number.Please try again.");
} else {
'''
}
int main()
{
int x, y, i,n=1,val;
printf("Please enter a number: \n");
scanf("%d", &x);
if (x!=1)
printf("The character you have entered is not a number.Please try again.");
return 0;
else
printf("What power is the number raised to?\n");
scanf("%d", &y);
Maybe if u do like that even if u entered a invalid character program will be end.

Printf and scanf not working properly? C programming [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 4 years ago.
I have a function that asks the user for user variable and user number.
void numReplace(char infix[50])
{
char userVar;
int userNum;
printf("Please enter the variable you want to change\n");
scanf("%c", &userVar);
printf("Please enter the replacement value for the variable\n");
scanf("%d", &userNum);
printf("%c %d", userVar, userNum);
int i=0;
char chrr;
infix[50] = '\0';
while((chrr=infix[i++])!='\0')
{
if (chrr == userVar){
chrr = userNum;
}
}
}
when running the program I should be asked the userVar and userNum. However the output is:
Please enter the variable you want to change
Please enter the replacement value for the variable
1
1
It only takes in one variable, I don't see a problem with my codes. Can someone help me?
Try adding a getchar(); after every call to scanf().
It's a workaround to the dangling newline character after you press <enter> when using scanf().
See this FAQ for more info.
This uservar may have received the \n you entered last time. If you have input before this input, please accept the newline with getchar().

While loop to validate input is a number in C? [duplicate]

This question already has an answer here:
Why inside a loop, scanf() with %d does not wait for the user input in case it received an invalid input previously?
(1 answer)
Closed 5 years ago.
So today I am trying to find a way to check if this input is a number. I cant find a way to make this code work so far. If I enter a number, the while loops ends, which is my intention. But, if I enter anything else, the code SHOULD print the printf once and then reprompt me for input (via the scanf statement back at the top of loop). But it instead prints the printf statement infinitely. How can I fix this?
float num1;
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number: ");
}
If scanf fails to preform the requested conversion, it will leave the input stream unchanged. So while your check is correct, you need to clean the input stream of the erroneous input before re-attempting to read a number again.
You can do it with scanf itself and and the input suppression modifier:
float num1;
while (scanf("%f",&num1)==0)
{
printf("Invalid input. Please enter a number: ");
scanf("%*s");
}
%*s will instruct scanf to parse the input as though it's attempting to convert a string of characters (removing characters in the process from the stream), but thanks to the asterisk, it won't attempt to write it anywhere.

Unable to execute a do-while loop completely [duplicate]

This question already has answers here:
Yes/No loop in C
(3 answers)
Closed 8 years ago.
I am trying to execute a small program using do-while.
#include<stdio.h>
#include<conio.h>
void main()
{
char another;
int num;
do
{
printf("Enter a number");
scanf("%d",&num);
printf("Square of %d id %d",num,num*num);
printf("Want to another another number y/n");
scanf("%c",&another);
}while(another=='y');
}
Now when I try to execute the program, it runs fine. I input a number and it displays its square. And then I see Want to enter another number y/n. But as soon as I press any key (y or n), the program exits itself before I can press enter to provide the input. I tried it many times but no success.
But the program runs fine if I ask the user to input either 1 or 2(in place of y/n). In that case it takes an integer input and can check the while block. If another == 1, the program runs again.
My problem is that why can't I check for a character in the while condition.
The reason it doesn't work is that after scanf gets num, the new line is still in the buffer, so it will be processed by the next scanf with %c format specifier. A direct way of fixing it is to use:
scanf(" %c", &another);
// ^space
Note that your original scanf("%c:,&another); won't compile, but I assume that's a typo. And always use int main, or it's undefined behavior.

Resources