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

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.
}

Related

Initializing and scanning a variable in C [duplicate]

This question already has answers here:
What does the scanf function return?
(5 answers)
Closed 8 months ago.
can anyone please help me out with this in C language
for ex:
int a = scanf("%d", &a);
doesn't assign the input value to a, but instead gives zero only always.
but this works as intended:
int a;
int a = scanf("%d", &a);
int a;
int a = scanf("%d", &a);
Does not compile because you redefine the variable a twice in the same scope.
scanf("%d", &a) attempts to parse the characters from stdin as the representation of an int and if successful stores the value to a and returns 1, otherwise returns EOF at end of file and 0 if characters are present but do not represent an int value in decimal representation.
Here is an example:
#include <stdio.h>
int main() {
int a, c, res;
for (;;) {
res = scanf("%d\n", &a);
switch (res) {
case 1: printf("value input is %d\n", a);
break;
case 0: printf("input is not a number\n");
break;
case EOF: printf("end of file detected\n");
return 0;
}
// read and discard the rest of the input line
while ((c = getchar()) != EOF && c != '\n')
continue;
}
}

scanf is not waiting for an integer input [duplicate]

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);

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.

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;
}

i have to use getchar(); twice to end program [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why doesn't getchar() wait for me to press enter?
I continue to learn C, and at this stage I have something that is not clear to me.
When I write a program, that has several printf();, at the end, where I ask a user to press Enter key to finish the program, I have to write getchar(); twice, because when I write it once it does not work. I use getchar(); only at the end of the program, nowhere else.
I work on Ubuntu. I write in C.
here is my latest work:
#include<stdio.h>
main()
{
int m,n,r,k,q,l;
printf("This program will help you to find GCD & LCM of 2 non-negative integers\n");
printf("Now, you'll be asked to enter your integers, press Enter to continue");
getchar();
printf("Enter first integer:");
scanf("%i", &m);
printf("Enter second integer:");
scanf("%i", &n);
while(m<0 || n<0)
{
printf("The integers cannot be negative! You'll be asked to enter integers again.\n");
printf("Enter first integer:");
scanf("%i", &m);
printf("Enter second integer:");
scanf("%i", &n);
}
while(m==0 && n==0)
{
printf("Both of the integers cannot be zero at the same time! You'll be asked to enter integers again.\n");
printf("Enter first integer:");
scanf("%i", &m);
printf("Enter second integer:");
scanf("%i", &n);
}
if(n>m)
{
int b;
b=n;
n=m;
m=b;
}
r=m%n;
if(r==0)
{
printf("The GCD of these integers is %i\n", n);
printf("The LCM of these integers is %i\n", m);
printf("Press Enter to finish");
getchar();
getchar();
return 0;
}
k=n%r;
while(k>0)
{
r=k;
k=q;
}
l=(m*n)/r;
printf("The GCD of these integers is %i\n", r);
printf("The LCM of these integers is %i\n", l);
printf("Press Enter to finish");
getchar();
getchar();
return 0;
}
The reason you need 2 getchar() is because
the last scanf() call left the ENTER waiting in the buffer
the 1st getchar() "ate" that ENTER
the 2nd getchar() waits for input.
To properly deal with user input, use fgets() and sscanf() instaed of the simpler scanf(). Define a buffer for these functions, for example
char buffer[1000];
and then replace your scanf() calls with the pair
fgets(buffer, sizeof buffer, stdin);
sscanf(buffer, "%d", &n);
In the future you might want to also check the return value of sscanf() to detect invalid inputs, like foo42ENTER
if (sscanf(buffer, "%d", &n) != 1) /* invalid input */;
Edit (using strtol() rather than sscanf() is even better -- thanks to #Scooter)
char buffer[1000];
char *err;
/* ... */
fgets(buffer, sizeof buffer, stdin); /* error checking ommited */
n = strtol(buffer, &err, 10);
/* error checking ommited */
/* ... */

Resources