This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 5 years ago.
program to count number of +ve, -ve and zeroes in the input.the printf statement in the for loop is executed more than once.how to correct this code.the count is correct but output is not in the expected format.
#include<stdio.h>
main()
{
int n,pc,nc,zc;
char s;
pc=nc=zc=0;
for(;1;) {
printf("do you wanna enter: y/n\n");
s=getchar();
if(s=='y') {
printf("enter num:\n");
scanf("%d",&n);
if(n>0) {
pc+=1;
}
if(n<0) {
nc+=1;
}
if(n==0) zc+=1;
}
if(s=='n') break;
}
printf("No.of +ve num: %d \n",pc);
printf("No.of -ve num: %d \n",nc);
printf("No.of zeroes: %d \n",zc);
}
output:
xplorer#kali:~/Desktop/docs/yk/chap3$ ./a.out
do you wanna enter: y/n
y
enter num:
4
do you wanna enter: y/n
do you wanna enter: y/n
y
enter num:
8
do you wanna enter: y/n
do you wanna enter: y/n
y
enter num:
-7
do you wanna enter: y/n
do you wanna enter: y/n
n
No.of +ve num: 2
No.of -ve num: 1
No.of zeroes: 0
\n is left behind in input buffer by previous call of getchar because it reads a character at a time. As '\n' is also a character, n next iteration getchar reads that left over \n .
You need to flush the input buffer:
int c;
while((c = getchar()) != '\n' && c != EOF);
...
{
printf("enter num:\n");
scanf("%d",&n);
...
The 'scanf' in the above snippet of the question code reads an integer from stdin, but only after the user presses return. The return character '\n' is also sent to stdin, however, the above 'scanf' is satisfied with reading only the integer value, and leaves the '\n' character in the stdin stream. The next time any function attempts to read from stdin, the '\n' character will be there to read. This is causing undesirable results in the question code here:
...
{
printf("do you wanna enter: y/n\n");
s=getchar();
....
The 'getchar' function read the '\n' character from stdin, and the program acts on it.
One way to avoid this problem is to have the 'scanf' function read the residual '\n' character from the buffer. This can be done by changing this:
scanf("%d",&n);
To this:
scanf("%d%*c",&n);
The latter reads the integer value from the stdin stream, and then reads (and discards) the residual '\n' character.
After each read from stdin, remove all additional characters from the buffer with:
/* discard (flush) remaining chars in stdin */
while (ch !='\n') ch = getchar();
As discussed in other answers, after you test with scanf or other input utilities, additional characters remain in the input buffer. You cannot reliably flush the input buffer with any standard function such as fflush as they apply to output buffers and not to input buffers. The simple while loop that scans for the newline insures that all characters are read regardless of whether a carriage return is present before the newline and is therefore portable between most OS's.
If curses.h is available on your system, You can use flushinp function to flush the input.
Check C FAQ: http://c-faq.com/stdio/stdinflush2.html
You have only checked for two conditions i.e 'y' or 'n' and not for the other so It might happen that it takes input other than 'y' or 'n'from previous inputs and loop continues. So just chk by printing if it is taking any other input and make changes accordingly.
Replace s=getchar(); with
do
{
s=getchar();
}while (isspace(s));
Things will start working.
Related
Here is something that confused me.
# include <stdio.h>
# include <limits.h>
int main()
{
int a;
int b;
printf("Enter two integers: ");
while(scanf("%d %d", &a, &b)!=2||b==0||a+b>INT_MAX||a*b>INT_MAX){
printf("Invalid entry, please re-enter: ");
while(getchar()=='\n');
}
printf("sum is %d, difference is %d, product is %lf, divid is %.2f, remainder is %d", a+b, a-b, (double)a*b, (float)a/b, a%b);
return 0;
}
With above code, if I enter "a 1" press ENTER:
Invalid entry, please re-enter:
pops up, then I enter "2 B" press ENTER, the last printf will execute.
However, if I change while(getchar()=='\n'); to while(getchar()!='\n');, and with the same entry (I enter "a 1" press ENTER)
Invalid entry, please re-enter:
pops up, then I enter "2 B" press ENTER), the last printf will not execute, and
Invalid entry, please re-enter:
pops up again.
What causes the difference here? How exactly do scanf and getchar work?
In the first case (while (getchar() == '\n');), the getchar() reads the a, but it isn't a newline, so the loop exits, leaving the space and the 1 in the input buffer. The repeated call to scanf() skips white space, reads 1, skips white space (newline included) and reads 2, leaving space and B in the input. Since the loop condition is now terminated (scanf() returned 2), the printf() is executed.
In the second case (while (getchar() != '\n');), this loop reads the a, the blank, the 1, and the newline before stopping. When you type 2 B, there aren't two numbers, so scanf() returns 1 and the main loop continues.
Note that your code will go into an infinite loop if you indicate EOF (usually Control-D on Unix, Control-Z on Windows) — at least, on most systems. You should always consider EOF. In context, you probably need something like:
int rc;
while (((rc = scanf(…)) != 2 && rc != EOF) || …)
You'd test rc against EOF before printing, too.
How do scanf and getchar work in C?
Sadly, they often do not work together well.
Code is a poor example of attempting to consume the rest of the input line when the input text is a problem.
If scanf("%d %d", &a, &b) failed to scan in 2 int, a prompt occurs and input is read with getchar until an Enter or '\n' happens.
If 2 int were scanned, various faulty tests are performed on a,b
// poor code
while(scanf("%d %d", &a, &b)!=2||b==0||a+b>INT_MAX||a*b>INT_MAX){
printf("Invalid entry, please re-enter: ");
while(getchar()=='\n');
}
The problem is that the code certainly intends to read a line of user input and then validate it. Unfortunately, scanf("%d %d" can consume multiple '\n' and leaves stdin with unclear contents when 2 int are not scanned. Code is an infinite loop on end-of-file.
Better to read a line of input with fgets(). Flushing stdout insures the prompt is seen before input is read.
char buf[80];
const char *prompt = "Enter two integers: ";
for (;;) {
fputs(prompt, stdout);
fflush(stdout);
if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EndOfFile_or_Error();
prompt = "Invalid entry, please re-enter: ";
int n;
if (sscanf(buf, "%d%d %n", &a, &b, &n) != 2) continue; // not 2 ints
if (buf[n]) continue; // extra text
if ((a < 0) ? (b < INT_MIN - a) : (b > INT_MAX - a)) continue; // + overflow
... // other tests
else break;
}
other tests
scanf() and getchar() read what is in the input buffer (stdin for standard input). When stdin is empty, the program will wait for the user to write something with the keyboard. When you press ENTER, the text you just wrote is stored in stdin. Then scanf() or getchar() can read something in stdin.
Notice that pressing ENTER will store a '\n' character (newline) in stdin.
A code like while( getchar() != '\n' ); is asking to getchar() to read one character from stdin while the character is not '\n'. It compares the return of getchar() with '\n'. So this is a way to "clean" the input buffer otherwise your program can go crazy.
EDIT
With the code you posted :
scanf() is called, you write "a 1", it tries to read a first integer but it is a character ('a') so it stops reading. printf() ask you to re-enter, then getchar() is called and reads the 'a'. Now scanf() is called a second time, reads the 1, then you have to enter something, you enter "2 B" so the second %d in scanf() can read the 2. Now the return of scanf() is 2, b is not 0 and the others conditions are false so the loop is ending. Notice that the 'B' character is still in stdin :)
I try to summarize what you need to know.
First, about your question. You do know the function of scanf is to read what the input (number) we give right? getchar on the other hand, is like scanf except that it is used for character/sentence only. You cannot use getchar to input number.
Second, there are no problem in your code except that it is okay not to use some line like that getchar line. It is also okay not to use while. Unless you want to make some condition, you may combine while with if / else function.
Third, you cannot input the number like you did: "1 a", "2 b". Those are considered invalid. This is because you are using %d in your scanf which refer to decimal number only. It means, you can input number 1-9 only and not the letters. So when the program asked to enter the 2 integers, you just type for example: 4 5. That's 4, space, 5. That is the correct way.
I try to write a program in C using the loop that repeated until a specific character is inputted from the keyboard. Here's my code:
#include <stdio.h>
main ()
{
char option;
do
{
printf("Enter q to quit: ");
option = getchar ();
}
while (option != 'q');
}
I've also tried with the scanf () but the result always the same. Here the output after I tried to test the program:
Enter q to quit: 3
Enter q to quit: Enter q to quit: 2
Enter q to quit: Enter q to quit: 1
Enter q to quit: Enter q to quit: q
Can anyone explain to me why the "Enter q to quit : " always appear twice and how can I fix it?
"Enter q to quit: " appears twice because your input buffer still has the new line character in it when it runs a second time.
Fix:
#include <stdio.h>
int main ()
{
char option;
do
{
printf("Enter q to quit: ");
option = getchar ();
while(getchar() != '\n'); //Enter this line here.
}
while (option != 'q');
}
When you enter q, you press q followed by enter (a new line character as far as C is concerned which is \n).
So when your loop returns to the beginning, '\n' is still in your input buffer and getch() automatically reads this and checks whether that equals q before returning to the beginning of your loop again (hence your text looks like it's printed twice).
Try using fgets like this:
fgets (option , 4 , stdin)
You have to make sure you have a character array big enough to hold this though so you should define
char option [3]; to hold 'q', the newline character '\n' and the termination character '\0';
fgets is quite a nice solution because it will only store up the the second argument worth of characters and throw away the rest. This means 1) you don't overflow your variables/arrays and 2) you don't have junk left in the input buffer :)
You get it printed twice because when you hit enter, a line feed character \n is appended to stdin.
You can discard that line feed character by adding an extra getchar:
do
{
printf("Enter q to quit: ");
option = getchar();
getchar(); // discard line feed
}while (option != 'q');
If you hit two keys, you'll read two characters. If you want to read characters, call getchar. If you want to read lines, call some function that reads lines.
getchar() function first reads from the buffer.If buffer is empty then and then it will read from standard input(i.e.screen).
getchar() is not working in the below program, can anyone help me to solve this out. I tried scanf() function in place of getchar() then also it is not working.
I am not able to figure out the root cause of the issue, can anyone please help me.
#include<stdio.h>
int main()
{
int x, n=0, p=0,z=0,i=0;
char ch;
do
{
printf("\nEnter a number : ");
scanf("%d",&x);
if (x<0)
n++;
else if (x>0)
p++;
else
z++;
printf("\nAny more number want to enter : Y , N ? ");
ch = getchar();
i++;
}while(ch=='y'||ch=='Y');
printf("\nTotal numbers entered : %d\n",i);
printf("Total Negative Number : %d\n",n);
printf("Total Positive number : %d\n",p);
printf("Total Zero : %d\n",z);
return 0 ;
}
The code has been copied from the book of "Yashvant Kanetkar"
I think, in your code, the problem is with the leftover \n from
scanf("%d",&x);
You can change that scanning statement to
scanf("%d%*c",&x);
to eat up the newline. Then the next getchar() will wait for the user input, as expected.
That said, the return type of getchar() is int. You can check the man page for details. So, the returned value may not fit into a char always. Suggest changing ch to int from char.
Finally, the recommended signature of main() is int main(void).
That's because scanf() left the trailing newline in input.
I suggest replacing this:
ch = getchar();
With:
scanf(" %c", &ch);
Note the leading space in the format string. It is needed to force scanf() to ignore every whitespace character until a non-whitespace is read. This is generally more robust than consuming a single char in the previous scanf() because it ignores any number of blanks.
When the user inputs x and presses enter,the new line character is left in the input stream after scanf() operation.Then when try you to read a char using getchar() it reads the same new line character.In short ch gets the value of newline character.You can use a loop to ignore newline character.
ch=getchar();
while(ch=='\n')
ch=getchar();
When you using scanf getchar etc. everything you entered stored as a string (char sequence) in stdin (standard input), then the program uses what is needed and leaves the remains in stdin.
For example: 456 is {'4','5','6','\0'}, 4tf is {'4','t','f','\0'} with scanf("%d",&x); you ask the program to read an integer in the first case will read 456 and leave {'\0'} in stdin and in the second will read 4 and leave {''t','f',\0'}.
After the scanf you should use the fflush(stdin) in order to clear the input stream.
Replacing ch = getchar(); with scanf(" %c", &ch); worked just fine for me!
But using fflush(stdin) after scanf didn't work.
My suggestion for you is to define a Macro like:
#define __GETCHAR__ if (getchar()=='\n') getchar();
Then you can use it like:
printf("\nAny more number want to enter : Y , N ? ");
__GETCHAR__;
I agree that it is not the best option, but it is a little bit more elegant.
Add one more line ch = getchar();
between scanf("%d",&x); and ch = getchar();
then your code work correctly.
Because when you take input from user, in this time you press a new line \n after the integer value then the variable ch store this new line by this line of code ch = getchar(); and that's why you program crash because condition can not work correctly.
Because we know that a new line \n is also a char that's why you code crash.
So, for skip this new line \n add one more time ch = getchar();
like,
ch = getchar(); // this line of code skip your new line when you press enter key after taking input.
ch = getchar(); // this line store your char input
or
scanf("%d",&x);
ch = getchar(); // this line of code skip your new line when you press enter key after taking input.
pieces of code work correctly.
This question already has answers here:
Why does scanf appear to skip input?
(7 answers)
Closed 8 years ago.
Here i have a simplified piece of code that asks and displays a number on a loop, it works fine for all numbers i type in, But if i input a letter or a special character (!"£$%^&*-_=+ etc ) it goes mental and skips the input.
#include<stdio.h>
int number;
int main()
{
do
{
system("cls");
printf("Enter a number");
scanf("%d",&number);
}
while(1==1);
}
My question is, what can i do to stop this from happening?, is there some code that filters out this nonsense or is scanf pretty much worthless?
//Edit: This is somehow been marked as a duplicate, heh.
From here:
if the input doesn't conform to the expected format scanf() can be
impossible to recover sensibly [..] A "better" alternative here is to
use an input function like fgets() or fgetc() to read chunks of input,
then scan it with sscanf() or parse it with string handling functions
like strchr() and strtol().
scanf with %d will fail to scan an integer and returns 0 when a character was entered. So just check if it doesn't return 1. If it doesn't , a character was entered (if it returned 0) or else, an integer was entered. Note that if EOF was encountered, scanf will return -1.
if(scanf("%d", &number) != 1)//character entered
{
printf("Invalid input\n");
scanf("%*s");//clear the invalid character(s) from stdin
}
else
{
//a number was entered
}
The reason that scanf becomes "mental" and the program prints Enter a number many times when you enter a character is that when the scanf fails to scan an integer from the standard input stream(stdin), it returns 0 and the execution continues. When scanf is called the next time, it sees the characters which you had entered the last time and again fails and this process continues. To prevent it, just clear the stdin like I've done in the code above.
Another popular way of clearing the stdin is using:
int c;
while((c = getchar()) != '\n' && c != EOF);
My program which finds prime factors is all set...the only thing left that I need to do is this type of output:
Do you want to try another number? Say Y(es) or N(o): y
//asks for another number (goes through the program again)
Do you want to try another number? Say Y(es) or N(o): n
//Thank you for using my program. Good Bye!
I have my attempt at this below...When I type n it does the correct output. But if I type 'y' it just says the same thing n does....How can I loop the entire program without putting the code for the program inside this while loop I have? So when I press y it goes through the program again?
int main() {
unsigned num;
char response;
do{
printf("Please enter a positive integer greater than 1 and less than 2000: ");
scanf("%d", &num);
if (num > 1 && num < 2000){
printf("The distinctive prime facters are given below: \n");
printDistinctPrimeFactors(num);
printf("All of the prime factors are given below: \n");
printPrimeFactors(num);
}
else{
printf("Sorry that number does not fall within the given range. \n");
}
printf("Do you want to try another number? Say Y(es) or N(o): \n");
response = getchar();
getchar();
}
while(response == 'Y' || response == 'y');
printf("Thank you for using my program. Goodbye!");
return 0;
} /* main() */
The problem is probably, that you're getting something that isn't y from getchar and the loop exits, as the condition is not matched.
getchar() may use a buffer, so when you type 'y' and hit enter, you will get char 121 (y) and 10 (enter).
Try the following progam and see what output you get:
#include <stdio.h>
int main(void) {
char c = 0;
while((c=getchar())) {
printf("%d\n", c);
}
return 0;
}
You will see something like this:
$ ./getchar
f<hit enter>
102
10
What you can see is that the keyboard input is buffered and with the next run of getchar() you get the buffered newline.
EDIT: My description is only partially correct in terms of your problem. You use scanf to read the number you're testing against. So you do: number, enter, y, enter.
scanf reads the number, leaves the newline from your enter in the buffer, the response = getchar(); reads the newline and stores the newline in response, the next call to getchar() (to strip the newline I described above) gets the 'y' and your loop exits.
You can fix this by having scanf read the newline, so it doesn't linger in the buffer: scanf("%d\n", &number);.
When reading input using scanf (when you enter your number above), the input is read after the return key is pressed but the newline generated by the return key is not consumed by scanf.
That means your first call to getchar() will return the newline (still sitting in the buffer), which is not a 'Y'.
If you reverse your two calls to getchar() - where the second one is the one you assign to your variable, your program will work.
printf("Do you want to try another number? Say Y(es) or N(o): \n");
getchar(); // the newline not consumed by the scanf way above
response = getchar();
just put getchar() after scanf statement of yours that will eat the unnecessary '\n' from buffer...
As others have stated, there is a single '\n' character in the input stream left over from your earlier call to scanf().
Fortunately, the standard library function fpurge(FILE *stream) erases any input or output buffered in the given stream. When placed anywhere between your calls to scanf() and getchar(), the following will rid stdin of anything left in the buffer:
fpurge(stdin);