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 */
/* ... */
Related
This is a snippet of my code. I'm confused why is digit can't function. It should if we input character/alphabet. The line is digit print "Please enter in numeric " but it doesn't print it. I need your opinion about this.
This my code:
printf("\nenter the amount of food to be purchased : ");
scanf("%d", &b);
printf("\n");
if (b >= 0) {
for (a=1; a<=b; a++){
printf("the price of food of- %d \t : ",a);
scanf("%d", &c);
printf("\n");
if (isdigit(c)) {
printf("Please enter in numeric !!\n");
while ((getchar()) != '\n');
system("PAUSE");
goto cashier;
}
printf("the amount ordered \t : ");
scanf("%d", &d);
printf("\n");
if (isdigit(d)) {
printf("Please enter in numeric !!\n");
while ((getchar()) != '\n');
system("PAUSE");
goto cashier;
}
scanf("%d", &c);. Reads an integer to c. When you call isdigit(c), you are not checking whether the input string is a number, you are checking whether the number inputted corresponds to an ascii character that represents a digit. This is not the intended behavior. What you want is this:
while (scanf("%d", &c) != 1) // Repeatedly get input until scanf reads 1 integer.
{
while (getchar()!='\n'); // Clear stdin.
puts("Please enter a number!");
}
// The resulting number is now stored in c.
This will try to read a number (not a string) into c. If the user does not enter 1 number, scanf() will not return 1 and the loop will try again. make sure that c is declared as an int and not a char, else numbers above 128 will overflow.
This question already has answers here:
Using fflush(stdin)
(7 answers)
Parsing input with scanf in C
(5 answers)
scanf() leaves the newline character in the buffer
(7 answers)
Closed 5 years ago.
#include <stdio.h>
int main()
{
char another;
int num;
do
{
printf("enter the number");
scanf("%d", &num);
printf("square of%d is %d\n", num, num * num);
printf("want to check another number y/n");
fflush(stdin);
scanf("%c", &another);
} while (another == 'y');
return 0;
}
In the above code, the second scanf() is not getting executed and hence the console is not accepting input.
According to the standard, flushing stdin is undefined behaviour. See Using fflush(stdin) for more information.
When you enter a number for the first scanf, its always followed by a newline. %d only takes the integer value and the newline is still left in the input buffer. So the subsequent scanf ends up consuming that character and your loop terminates due to another=='y' being false. (another has '\n').
Following is one of the ways to solve the problem. Use a %c along with %d to capture newline and ignore it.
#include<stdio.h>
int main()
{
char another, nl;
int num;
do
{
printf("enter the number");
scanf("%d%c",&num,&nl);
printf("square of%d is %d\n",num,num*num);
printf("want to check another number y/n: ");
//fflush(stdin);
scanf("%c",&another);
printf("%c", another);
}while (another=='y');
return 0;
}
if you add the statement
fseek(stdin, 0, SEEK_END);
it will move the stdin pointer to the end of the file so any extra character will be omitted. then write the second scanf. I mean:
#include<stdio.h>
int main()
{
char another, nl;
int num;
do
{
printf("enter the number");
scanf("%d%c",&num,&nl);
fseek(stdin, 0, SEEK_END);
printf("square of%d is %d\n",num,num*num);
printf("want to check another number y/n: ");
//fflush(stdin);
scanf("%c",&another);
fseek(stdin, 0, SEEK_END);
printf("%c", another);
}while (another=='y');
return 0;
}
Cause of the char input before scanf dont work
remove the fflush and add a space to <<"%c">>
like this: scanf(" %c",&another);
#include<stdio.h>
int main(){
char another;
int num;
do
{
printf("enter the number ");
scanf("%d",&num);
printf("square of %d is %d\n",num,num*num);
printf("want to check another number y/n ");
scanf(" %c",&another);
}while (another=='y');
return 0;
}
This works great
First of all fflush; flushes the output buffer of a stream, so you should not be using it here. The reason why the second scanf is not working is because you are trying to read a 1-bit character which in this case always getting the value of \0 after the second printf statement. Hope this helped.
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.
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;
}
Here is the code for main():
int main (void)
{
float acres[20];
float bushels[20];
float cost = 0;
float pricePerBushel = 0;
float totalAcres = 0;
char choice;
int counter = 0;
for(counter = 0; counter < 20; counter++)
{
printf("would you like to enter another farm? ");
scanf("%c", &choice);
if (choice == 'n')
{
printf("in break ");
break;
}
printf("enter the number of acres: ");
scanf("%f", &acres[counter]);
printf("enter the number of bushels: ");
scanf("%f", &bushels[counter]);
}
return 0;
}
Every time the program runs through the first scanf works fine but on the second pass through the loop the scanf to enter a character does not run.
Add a space before %c in scanf. This will allow scanf to skip any number of white spaces before reading choice.
scanf(" %c", &choice); is the only change required.
Adding an fflush(stdin); before scanf("%c", &choice); will also work. fflush call will flush the contents of input buffer, before reading the next input via scanf.
In case of scanf(" %c", &choice); even if there is only a single character in the input read buffer, scanf will interpret this character as a valid user input and proceed with execution. Incorrect usage of scanf may result in a series of strange bugs [like infinite loops when used inside while loop].