inside while loop used fflush does not work - c

#include<stdio.h>
int main(){
char arr[20];
int a;
int count=0;
while(1){
printf("enter string with space:");
fflush(stdin);
scanf("%[^\n]%*c", arr);
printf("enter integer:");
scanf("%d",&a);
count++;
if(count==4){
break;
}
}
}
I want to read string with space and I have to use this code. I wrote this in while loop and I want to read string and after integer number and it does not work.
Output:
enter string with space:hey hey
enter integer:159
enter string with space:enter integer:
But output should be:
enter string with space:hey hey
enter integer:159
enter string with space:.... heyy
enter integer: 1235

fflush() is not defined input streams such as stdin. You will find that it works on Microsoft's C library, but not GNU.
Your scanf() call is incorrect. The first format specifier is incorrect, and you have no format specifier for string ;
scanf("%*[^\n]%*c") ;
will discard any remaining buffered characters to the end of the line inclusive. It accepts no input - it is not clear what string is or what you want to do with it. I'd suggest using a separate input call for that, for clarity.
Another somewhat less arcane solution is:
int c ;
while ((c = getchar()) != '\n' && c != EOF) { }

enter string with space:enter integer:
This happens because after you enter integer input, \n is still left in the stream. %[ does not skip leading whitespace unlike most other format specifiers. Change scanf("%[^\n]%*c", arr); to scanf(" %[^\n]%*c", arr); so it manually skips the leading whitespace before taking input.
As for fflush(stdin), that is undefined behavior (see Using fflush(stdin)). #Clifford already provides two nice solutions to that issue.

Related

Why is fgets waiting for input before it's even called?

I'm trying to write a simple program to read an integer and then a string, then print both to standard output. Ideally, the execution should look something like this:
Input the number.
> 10
Input the string.
> a string
number: 10
string: a string
However, when I run the program, it freezes after the call to scanf() until more input is provided.
Input the number.
> 10
a string
Input the string.
>
number: 10
string: a string
Why is it waiting for input before fgets() is ever called?
#include <stdio.h>
int main()
{
int number;
char string[32];
printf("Input the number.\n> ");
scanf("%d\n", &number);
printf("\nInput the string.\n> ");
fgets(string, 32, stdin);
printf("\nnumber: %d\nstring: %s\n", number, string);
}
From a previous post...
https://stackoverflow.com/a/5918223/2203541
#include <stdio.h>
int main()
{
int number;
int c;
char string[32];
printf("Input the number.\n> ");
scanf("%d", &number);
do
{
c = getchar();
} while (c != '\n');
printf("\nInput the string.\n> ");
fgets(string, 32, stdin);
printf("\nnumber: %d\nstring: %s\n", number, string);
}
"Why is fgets waiting for input before it's even called"
fgets() does not act until it is called, but if when called, and if pointing to stdin and there is content remaining in the stdin stream, it will consume it immediately. If that contents contained EOF, n-1, OR a newline (read link) execution flow will continue.
The problem here is that scanf() (called prior to fgets()) is notorious for doing exactly what it is asked to do. For example, upon user entering 12<return> two recognizable items are entered into stdin, digits and a newline but by using "%d" as the format specifier, only the first of those items is consumed, leaving the \n hanging, until the very next call to fgets(), which accepts it as input, allowing execution flow to resume immediately (as described above), causing the apparent skip you are seeing.
[This is one (of several) examples that will provide a work around for the scanf() issue:
Change this:
printf("Input the number.\n> ");
scanf("%d", &number);//leaves the newline
To this:
char c;
...
printf("Input the number.\n> ");
scanf("%d%c", &number, &c);//consumes the newline
From comments:
"is there a way to use fgets to read an integer"
Yes, I prefer fgets() coupled with your favorite string to number converter. (There are several) The simplest is this:
char cNum[10];
int num;
printf("Input the number.\n> ");
if(fgets(cNum, sizeof cNum, stdin))
{
num = atoi(cNum);
}
else //handle error
See also strtol() for a more robust solution.
Alright, so I played around with it some more and did a little more studying on scanf() format syntax, and figured out a solution. Apparently, putting the whitespace character at the end of my scanf call there tells it to keep reading until it finds something AFTER the whitespace, so of course it would hang up there until you give more input.
Remove the whitespace character in the scanf formatter, and add a leading space to the following scanf call.
The reason I had used fgets originally was so I could specify a buffer length to avoid overflow. Apparently, the same effect can be achieved using %32s in the scanf call. The fixed code looks like this:
#include <stdio.h>
int main()
{
int number;
char string[32];
printf("Input the number.\n> ");
scanf("%d", &number);
printf("\nInput the string.\n> ");
scanf(" %32s", &string);
printf("\nnumber: %d\nstring: %s\n", number, string);
}

How to prompt the user to enter an integer and a character from the keyboard in C [duplicate]

This question already has an answer here:
How to read / parse input in C? The FAQ
(1 answer)
Closed 4 years ago.
I am trying to figure out the best way to get an integer and a character from a user
Here is what I have so far:
#include <stdio.h>
int main()
{
int a;
char b;
printf("enter the first number: \n");
scanf("%d", &a);
printf("enter the second char: \n");
scanf("%c", &b);
printf("Number %d",a);
printf("Char %c",b);
return 0;
}
The output is not shown correctly. Is there any problem with this?
Your input and output statements are fine. Just replace printf("Number %d",a); with printf("Number %d\n",a); to better format the output. Also you should change your second scanf statement to scanf(" %c", &b);. This will deal with the newline character entered after the number is inputted.
After you enter the number, you pressed the Enter key. Since the scanf function works on the input stream, when you try to process the next char after reading the number, you are not reading the character you typed, but the '\n' character preceding that. (i.e. because the Enter key you pressed added a '\n' character to your input stream, before you typed your char)
You should change your second call to scanf with the following.
scanf(" %c", &b);
Notice the added space character in the formatting string. That initial space in the formatting string helps skip any whitespace in between.
Additionally, you may want to add \n at the end of the formatting strings of both printf calls you make, to have a better output formatting.
Here you need to take care of hidden character '\n' , by providing the space before the %c in scanf() function , so the "STDIN" buffer will get cleared and scanf will wait for new character in "STDIN" buffer .
modify this statement in your program : scanf("%c",&b); to scanf(" %c",&b);

getchar() not working in c

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.

Odd loop does not work using %c [duplicate]

This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 8 years ago.
I am leaning C programming. I have written an odd loop but doesn't work while I use %c in scanf().Here is the code:
#include<stdio.h>
void main()
{
char another='y';
int num;
while ( another =='y')
{
printf("Enter a number:\t");
scanf("%d", &num);
printf("Sqare of %d is : %d", num, num * num);
printf("\nWant to enter another number? y/n");
scanf("%c", &another);
}
}
But if I use %s in this code, for example scanf("%s", &another);, then it works fine.Why does this happen? Any idea?
The %c conversion reads the next single character from input, regardless of what it is. In this case, you've previously read a number using %d. You had to hit the enter key for that number to be read, but you haven't done anything to read the new-line from the input stream. Therefore, when you do the %c conversion, it reads that new-line from the input stream (without waiting for you to actually enter anything, since there's already input waiting to be read).
When you use %s, it skips across any leading white-space to get some character other than white-space. It treats a new-line as white-space, so it implicitly skips across that waiting new-line. Since there's (presumably) nothing else waiting to be read, it proceeds to wait for you to enter something, as you apparently desire.
If you want to use %c for the conversion, you could precede it with a space in the format string, which will also skip across any white-space in the stream.
The ENTER key is lying in the stdin stream, after you enter a number for first scanf %d. This key gets captured by the scanf %c line.
use scanf("%1s",char_array); another=char_array[0];.
use getch() instead of scanf() in this case. Because scanf() expects '\n' but you are accepting only one char at that scanf(). so '\n' given to next scanf() causing confusion.
#include<stdio.h>
void main()
{
char another='y';
int num;
while ( another =='y')
{
printf("Enter a number:\t");
scanf("%d", &num);
printf("Sqare of %d is : %d", num, num * num);
printf("\nWant to enter another number? y/n");
getchar();
scanf("%c", &another);
}
}

Dev-C++ Input skipped

#include<stdio.h>
#include<conio.h>
main()
{
int i;
char c, text[30];
float f;
printf("\nEnter Integer : ");
scanf("%d",&i);
printf("\nEnter Character : ");
c = getch();
printf("\nEnter String:");
gets(text);
printf("\nEnter Float:");
scanf("%f",&f);
printf("\nInteger : %d",i);
printf("\nCharacter : %c8",c);
printf("\nString : %s",text);
printf("\nFloat : %f",f);
getch();
}
Why is this simple program not able to read a string using the gets() function? What else should I use to correct it? Well it it worked in Turbo C in my old 32-bit PC but not here...
Scanf or other input parsing functions take only required quantity of characters as specified in the call from stdin and reject others.As a result these rejected values,during next read of stdin enter into the variables along with the newline characters and thus skipping inputs for a few calls.So its better to call a clear routine that cleans stdin and stops garbage entering into other variables.
Although your code is quite vulnerable still it has solution:-
#include<stdio.h>
int clear()
{
while ((getchar())^'\n');
}
int main()
{
int i;
char c, text[30]={0};
float f;
printf("\nEnter Integer : ");
scanf(" %d",&i);
printf("\nEnter Character : ");
scanf(" %c",&c);
printf("\nEnter String:");
clear();
gets(text);
printf("\nEnter Float:");
scanf(" %f",&f);
printf("\nInteger : %d",i);
printf("\nCharacter : %c",c);
printf("\nString : %s",text);
printf("\nFloat : %f",f);
getchar();
}
With some little research, I guess that the problem comes with scanf(). scanf() reads a line without the end of line character '\n' which seems to stay in the buffer and actually red by the next statement.
alternatively you can use fgets() and sscanf() as follows:
To read a character I used:
fgets(text,sizeof(text),stdin);
sscanf(text,"%c",&c); /* or: c = text[0]; */
to read an integer I have used
fgets(text,sizeof(text),stdin);
sscanf(text,"%d",&i);
I had a major problem with gets() in a C course I had (to which DevC++) was advised as a compiler. However, I totally recall I didn't follow the advice and it turned out that the behavior of fgets() is also compiler dependent.
The man page for gets() has this:
BUGS
Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Use fgets() instead.
When you type 42 (or whatever) as the first integer, you actually type three characters: 4, 2 and then the newline character that comes from pressing ENTER. Your first scanf reads an integer, which means that it only reads the 4 and the 2, leaving the newline character in the input buffer.
When your program gets to gets, it reads a the very short line that consists just of that newline character.
You can fix it by reading and throwing away the newline character just after scanf, something like this:
printf("\nEnter Integer : ");
scanf("%d",&i);
while (getchar() != '\n')
;

Resources