scanf is not waiting for an integer input [duplicate] - c

This question already has answers here:
Validate the type of input in a do-while loop
(5 answers)
While-loop ignores scanf the second time
(3 answers)
Closed 4 years ago.
printf("Enter an integer: ");
status = scanf("%d", &integer);
if (status == 0){
do{
printf("Please enter an integer: ");
status = scanf("%d", &integer);
}
while (status == 0);
}
I'm trying to prevent a user from entering a data of type of character. However, after the prompt, "Please enter an integer: ", it doesn't wait for an input. Hence, it goes into an infinite loop whenever I enter a letter at the first prompt. How do I fix this? Any heeelp will be greatly appreciated!

You need clean the buffer first, you can use fflush(stdin); like this:
int integer, status=0;
if (status == 0)
{
do
{
printf("\nPlease enter an integer: ");
status = scanf("%d", &integer);
fflush(stdin);
}
while (status == 0);
}
It's not in standard C using fflush(stdin) but you can clean the buffer in other ways.
You can build your own function to clean the buffer, like this:
void flushKeyBoard()
{
int ch; //variable to read data into
while((ch = getc(stdin)) != EOF && ch != '\n');
}
To clean the screen call this function:
void clrscr()
{
system("#cls||clear");
}
Final code:
#include <stdio.h>
void clrscr()
{
system("#cls||clear");
}
void flushKeyBoard()
{
int ch; //variable to read data into
while((ch = getc(stdin)) != EOF && ch != '\n');
}
int main()
{
int integer, status=0;
if (status == 0)
{
do
{
printf("\nPlease enter an integer: ");
status = scanf("%d", &integer);
flushKeyBoard();
clrscr();
}
while (status==0);
}
}

your %integer, should be declared int.
Like that:
int integer;
printf("Please input an integer value: ");
scanf("%d", &integer);

Related

Why non-integer inputs cause infinite loop?

When I enter a non-integer value it cause an infinite loop. Do I need to replace scanf? If so how can I do that.
int num=1;
if(num==1){
int slct;
printf("\n\tWelcome");
printf("\n1. Login\n2. Register\n3. Account\n4. Exit\n");
SELECTION: ;
printf("\n\tEnter a number:");
scanf("%d",&slct);
if (slct == 1){}
else if (slct == 2){}
else if (slct == 3){}
else if (slct == 4){
return 0;
} else {
goto SELECTION;
}
}
You need to check the return value of scanf and flush the input:
#include <stdbool.h>
#include <stdio.h>
int main()
{
bool done = false;
while (!done) {
printf("\n\tWelcome\n");
printf("1. Login\n");
printf("2. Register\n");
printf("3. Account\n");
printf("4. Exit\n\n");
printf("Enter a number:");
int selection;
int result = scanf("%d", &selection);
if (EOF == result) {
done = true;
}
else if (1 != result) {
printf("You did not enter a valid number\n");
int c;
while ((c = getchar()) != '\n' && c != EOF) {}
done = (c == EOF);
}
else if (1 == selection) {
printf("You chose login\n");
}
else if (2 == selection) {
printf("You chose register\n");
}
else if (3 == selection) {
printf("You chose account\n");
}
else if (4 == selection) {
done = true;
}
else {
printf("Please pick a number between 1 and 4\n");
}
}
}
The format string in scanf("%d",&slct); is %d which means you want to read a number.
When you enter something else than a number, scanf returns 0 to indicate that zero numbers were read.
If the scanf encounters and end-of-file when attempting to read the input (enter control-D) then it returns the special value EOF.
Also, scanf does not consume the incorrect input, so you need to explicitly flush it.

Check number input and ask it until he enters a number [duplicate]

This question already has answers here:
How to scanf only integer?
(9 answers)
Closed 4 years ago.
I want to check the user input if it is a number and I want the program to accept only a number as an input. I don't know if I explained myself clearly, I'll try by showing you an example:
int x;
printf("Write a number: ");
scanf("%d", &x);
while(!isdigit(x))
{
printf("Not valid\n");
fflush(stdin);
scanf("%d", &x);
}
I tried using scanf("%d", &x) != 1 as a while condition but it remains inside the loop. Is there a way to ask an input until the user writes a number? For now I just return the function but I'd like not to.
You have to check the return value of scanf():
#include <stdio.h>
int main(void)
{
int x;
while (printf("Write a number: "),
scanf("%d", &x) != 1) // when the number of successful conversion wasn't 1
{
fputs("Not valid!\n", stderr);
int ch;
while ((ch = getchar()) != EOF && ch != '\n'); // clear stdin from garbage
} // that might be left.
}

C coding: Can't seem to understand why code doesn't wait for standard input, but if I run independently it works fine [duplicate]

This question already has answers here:
fgets doesn't work after scanf [duplicate]
(7 answers)
Closed 6 years ago.
I will try to explain the issue here.
I have written this code that accepts various types of inputs:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int main()
{
int number;
printf("press <ENTER> to continue...");
while( getchar() != '\n' );
char *p, s[100];
int n=0;
printf("enter a number: ");
while (fgets(s, sizeof(s), stdin))
{
n = strtol(s, &p, 10);
if (p == s || *p != '\n')
{
printf("Invalid integer, please try again: ");
}
else
break;
}
printf("You entered: %d\n", n);
printf("Enter an integer between 10 and 20: ");
scanf("%d", &number);
while (1)
{
if (number < 10 || number > 20)
{
printf("Invalid value, 10 < value < 20: ");
scanf("%d", &number);
}
else
{
break;
}
}
printf("You entered: %d\n", number);
//part 3
double decpart;
printf("Enter a floating number num: ");
char buf[100];
int len;
char *endptr;
while (1)
{
fgets(buf,sizeof(buf),stdin);
len = strlen(buf)-1;
// right strip spaces (replace by linefeed like fgets ends the input)
while(len>0)
{
len--;
if (buf[len]==' ')
{
buf[len]='\n';
}
else
{
break;
}
}
double floatnum = strtod(buf,&endptr);
if (endptr[0]!='\n')
{
printf("Invalid floating point number, enter again: ");
}
else
{
int intpart = (int)floatnum;
double decpart = floatnum - intpart;
if (decpart == 0.000000){
printf("Invalid floating point number, enter again: ");
}
else
{
printf("Number entered = %.2f\n", floatnum);
break;
}
}
}
double floatnum1;
printf("Enter a floating point number between 10.00 and 20.00: ");
scanf("%lf", &floatnum1);
while (1)
{
if (floatnum1 < 10.00 || floatnum1 > 20.00)
{
printf("Invalid value, 10.000000 < value < 20.000000: ");
scanf("%lf", &floatnum1);
}
else
{
break;
}
}
printf("You entered: %0.2lf\n", floatnum1);
printf("End of tester program for milestone one!\n");
return 0;
}
Problem occurs on Part 3 of this code. I see on screen Enter a floating number num: and immediately without waiting for user input it prints Invalid floating point number, enter again:
This is not the case if I just run part3(commented here in code as //part3) independently, it just works fine.
Any idea, why that is happening?
The reason for this behaviour lies in the usage of scanf followed by fgets
scanf reads a number from standard input, and stops as soon as it encounters a non-digit character, which is the newline in this case.
Next fgets reads a whole line. But now there's still the single newline in the input, which satisfies fgets even though this is only an empty line.
When you skip over whitespace and finally check for a newline, endptr only points to a \0 character. Thus the message
Invalid floating point number, enter again:
To fix this, you must first skip whitespace before reading further with fgets.

Entering a character instead of integer

I'm using a do-while loop to print a menu to the screen. And I'm reading choice as an integer. The proplem is that if the user enter a character the program blows up. How can I avoid that?
#include <stdio.h>
int menu() { // prints the main menu of labs///
int choice;
printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
scanf("%d", &choice);
return choice;
}
int main() {
int choice;
do {
choice = menu();
if (choice != 4) {
if (choice == 1)
//lab5(choice);
else if (choice == 2)
//lab10(choice);
else if (choice == 3)
// lab11(choice);
else
printf("invalid choice\n");
}
} while (choice != 4);
return 0;
}
This should work for you, you need to check the return value of scanf
int menu() { // prints the main menu of labs///
int choice;
printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
if(scanf("%d", &choice) == 1)
{
return choice;
}
else
{
return 0;
}
}
The scanf() (and family of functions) returns the number of successful conversions from the input buffer, if the conversion (%d) fails the function returns 0 (or EOF). In this case the character that could not be converted is not removed from buffer, this is why the endless loop occur, the conversion keeps failing for ever.
I used this method to flush the input buffer after the scanf call and the program behaved as expected.
Run the program online (don't know for how long this will stay up)
void flushInput(){
int c;
while((c = getchar()) != EOF && c != '\n')
/* discard */ ;
}
int menu() { // prints the main menu of labs///
int choice;
printf("1)Lab 5 ( Repetetitions ).\n2)Lab 10 ( Passing 1D-Arrays to functions ).\n3)GPA Calculation.\n4)EXIT.\n\nEnter your choice: ");
if(scanf("%d", &choice) != 1){
flushInput();
return 0;
}else{
flushInput();
return choice;
}
}
/*USE This Code*/
#include <stdio.h>
#include <stdlib.h>
void orderAsk(int orderStorage[1]);
int main()
{
int orderStorage[1];
orderAsk(orderStorage);
printf("%d",orderStorage[0]);
return 0;
}
void orderAsk(int orderStorage[1]){
int d;
d = scanf("%d", &orderStorage[0]);
if ( d!= 1) {
system("cls");
fflush(stdin);
printf("Error! Re-Enter\n");
orderAsk(orderStorage);
}
}

Checking input types with scanf() in a while loop [duplicate]

This question already has answers here:
Why is scanf() causing infinite loop in this code?
(16 answers)
Closed 7 years ago.
I've been writing a program that takes an input and checks if the number is even or odd and outputs an error message if the input is a character not a number my initial code was:
int main()
{
int x;
int check = scanf("%d", &x);
printf("input: ");
while(check != 1){ //means that the input is inappropriate
printf("Error!: unexpected input\n");
printf("input: ");
check = scanf("%d", &x);
}
if(x%2 == 0){
printf("It's even\n");
}else{
printf("It's odd\n");
}
return 0;
}
when I run an infinite loop printing "Error!: unexpected input\n"
but when I put the following statement in the while loop it works properly the statement is : scanf("%s",&x);
can somebody explains this behavior?
int check = scanf("%d", &x); does not consume the "input is a character not a number", leaving that input in stdin for the next input function. Since the next input function is check = scanf("%d", &x);, it does not consume the offending data and so the cycle repeats.
Code needs to read the "input is a character not a number" with something other than scanf("%d", ...)
Rather than mess with a little fix, recommend never using scanf(). Read input with fgets() or getline() and then parse with ssscanf(), strtol(), etc.
int main(void) {
int x;
char buf[100];
while (printf("input: "), fgets(buf, sizeof buf, stdin) != NULL) {
int check = sscanf(buf, "%d", &x);
if (check == 1) break;
printf("Error!: unexpected input\n");
}
if(x%2 == 0){
printf("It's even\n");
}else{
printf("It's odd\n");
}
return 0;
}

Resources