This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 8 years ago.
#include "stdio.h"
int main(void)
{
int order, nextp, N=3;
char cont;
nextp = 0;
printf("\nShould we continue (y or n): ");
scanf("%c", &cont);
if (cont != 'y') return;
for(; nextp < N; nextp++)
{
printf("Enter order number: ");
scanf("%d", &order);
printf("you have entered %d\n", order);
printf("okay now continue with cont\n");
printf("enter cont y or n: ");
scanf("%c", &cont);
if (cont != 'y')
{
printf("\nnot equal to y\n");
break;
}
printf("after intepreting t[0]");
}
return 0;
}
The output looks like this
Should we continue (y or n): y
Enter order number: 45
you have entered 45
okay now continue with cont
enter cont y or n:
not equal to y
The second input was skipped. Why?
because of newline character already in stdin , this is happening.
use
scanf(" %c", &cont);
instead of
scanf("%c", &cont);
note one space before %c.
After scanf("%d", &order); consumes the number (45 in this case), there is still a newline left after that. You can use scanf("%d\n", &order) to make it consume the return.
Another answer to this can be found here:
scanf() leaves the new line char in buffer?
This is why scanf is not typically preferred for character input. There's a left over carriage return after the previous input.
For example, if you were to add a getchar() after the order input, your problem would be solved, but that's not clean code. You can also see this explicitly by subsituting cont != 'y' to cont != '\n'.
Instead, use getchar() for all your input and check for \n
For most conversions scanf will skip whitespace, but for char format ("%c") you must skip white space by using an explicit space in the format (" %c") as explained here:
C - trying to read a single char
This is also explained in the scanf documentation, but it's confusing and may be better to use something else as others have mentioned.
You can use fflush()
printf("enter cont y or n: ");
fflush(stdin);
scanf("%c", &cont);
Related
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:
C: Do-While Loop Repeating Too Much!
(3 answers)
Closed 9 years ago.
#include <stdio.h>
int main(void) {
char c = 'y', temp;
printf("Press y\n");
do {
printf("Press y to continue\n"); // read y again and again
scanf("%c", &c); // y entered
printf("%c", c); // loop should repeat but doesn't repeat
} while(c == 'y');
}
It will not. Because scanf reads the \n character on second iteration which cause the loop to terminate. Place a space before %cto consume this \n character left behind by previous scanf.
scanf(" %c",&c);
Try adding a space before %c which is a scanf quirk. The space absorbs the newline char after typing the 'y'.
scanf(" %c",&c);
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 4 years ago.
I want to know the reason why this code not run properly
#include<stdio.h>
main()
{
char a;
int n;
do
{
printf("enter the number");
scanf("%d",&n);
printf("the squre is %d",n*n);
printf("want any more so Y for yes N for no");
scanf("%c%[^\n]",&a);
}while(a=='Y');
}
Reasons are
1. scanf("%c%[^\n]",&a); needs two parameters. Remove %[^\n].
2. \n character left behind by the previous scanf on pressing Enter key. Next scanf will read this \n character in the buffer. You need to consume this \n. Use a space before %c specifier to eat up this \n.
Try this:
scanf(" %c",&a);
↑ A space before %c specifier
A space before %c specifier is able to eat ant number of newline characters.
Your code after modification:
#include<stdio.h>
int main(void)
{
char a;
int n;
do
{
printf("enter the number\n");
scanf("%d",&n);
printf("the squre is %d\n",n*n);
printf("want any more so Y for yes N for no\n");
scanf(" %c",&a);
}while(a=='Y');
return 0;
}
Here is a solution to your problem.
#include<stdio.h>
main()
{
char a;
int n;
do
{
printf("enter the number");
scanf("%d",&n);
a = getchar(); // <-- Here is a change.
printf("the squre is %d",n*n);
printf("want any more so Y for yes N for no");
while(a == '\n') a = getchar();
}while(a=='Y');
}
What actually is making you problem is this line.
scanf("%d",&n);
Suppose, you entered 10 then pressed 'Enter', now scanf() takes 10 and leaves a newline behind in the buffer. It is making problem. By getchar() you are eating up that new line each time after taking a input with scanf. Yes there are other solutions too with scanf() tricks but it seems simpler to me. So I shared it.
just use scanf(" %c",&a); and could be done.
Wrong code: scanf("%c%[^\n]",&a);
Right code: scanf(" %c%*[^\n]",&a);
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].
I can't see why does the While loop just speed away and skipping the scanf for the char?
It would not even ask for my input and just loop like there's no tomorrow.
#include <stdio.h>
int main()
{
int number;
int multiply, ans;
char choice;
printf("-------------------------------------");
printf("\n MULTIPLICATION TABLE ");
printf("\n-------------------------------------");
do
{
printf("\nEnter an integer number:");
scanf("%d", &number);
printf("\nMultiplication of %d is :-\n", number);
printf("\n");
for(multiply=1; multiply<11; multiply++){
ans = number * multiply;
printf(" %d", ans);
}
printf("\n");
printf("\nWould you like to continue? [Y] for Yes,[N] for no : ");
scanf("%c", &choice);
printf("\n");
}
while(choice='Y');
printf("Thank You");
return 0;
}
scanf() doesn't do what you think it does (newline characters, buffering, etc.). It's preferred to use fgetc():
choice = fgetc(stdin);
For the same reason, you need to get rid of the trailing newline that
scanf("%d", &number");
leaves in the standard input buffer. To fix this, insert
fgetc(stdin);
after that particular call to scanf().
Also, C is not Pascal. The equality comparison operator - and the condition - you're looking for is
while (choice == 'Y')
the single equation mark denotes an assignment.
I think you need to use == operator for the comparison in while condition check as:
while(choice=='Y');
Currently you are using = operator, which is assigning Y to choice variable.
It has been a long time since I programmed in that language, but at a glance, you have:
while(choice='Y');
instead of:
while(choice=='Y');
== compares, = sets equal to. So the while loop is actually not checking the condition you're trying to set.