2

Is there any other method to clear the input buffer in c withut using

 fflush(); 

or

 while(getchar()!='\n'); 

Because i have read it everywhere and cant find any other way to do it.

10
  • How about while (scanf("%c",&c) == 1)? Commented Dec 3, 2014 at 13:46
  • @barakmanos sorry sir, but din't you mean while (scanf("%c",&c) == 1);? Commented Dec 3, 2014 at 13:47
  • rewind(stdin); and fseek(stdin,0,SEEK_END); might work although i've not tested it... Commented Dec 3, 2014 at 13:47
  • 2
    What is the use-case where you need something other than this? Commented Dec 3, 2014 at 13:53
  • 1
    @JonatanGoebel , Using fflush on stdin is Undefined Behaviour Commented Dec 3, 2014 at 14:28

3 Answers 3

2

The best solution is to not depend on the input buffer's state so much.

Read input as whole lines, using fgets(), then parse those. Don't use e.g. scanf() to read individual values, since it interacts with the buffer in annoying ways.

Sign up to request clarification or add additional context in comments.

1 Comment

But i m talking about the case eg when using getchar( ) some "/n " or other characters which have not been read interferes with the functioning .using fgets() or getline() is another issue thanks for the reply though .
2

Using fgets() as suggester @unwind best approach.

To flush to the end of the line.

void FlushStdin(void) { int ch; while(((ch = getchar()) !='\n') && (ch != EOF)); } 

If stdin is all ready flushed to the end-of-line, calling FlushStdin() or other posted scanf(), fgetc() solutions, will flush to the end of the next line.

Note scanf("%*[^\n]%*1[\n]"); does not work if the next char is '\n'.

Comments

2

Another method to clear the input buffer (stdin) would be to use

scanf("%*[^\n]"); scanf("%*c"); 

%*[^\n] instructs scanf to scan everything until a new-line character(\n) and then discards it. The %*c tells scanf to scan and discard a single character which in this case will be the newline character.

4 Comments

flushstdin.c:9:5: warning: unknown conversion type character ‘*’ in format [-Wformat=]
"Here, %*[^\n] instructs scanf to scan everything until a new-line character(\n) is found and then discard it." is not true if the first char is '\n'. '\n' remains in stdin.
Using %*c instead of %*1[\n] does not solve the problem when input is only '\n' as that 2nd part of the format specifier is not reached. Instead code code code use 2 independent scanf() calls: scanf("%*[^\n]"); scanf("%*1[\n]"); or scanf("%*[^\n]"); getchar();.
@chux ,Isn't the % at the end of scanf("%*[^\n]%"); a typo? Anyway,Thanks for making me understand!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.