Clear standard input buffer for C program in Linux


 
Thread Tools Search this Thread
Top Forums Programming Clear standard input buffer for C program in Linux
# 1  
Old 08-08-2014
Ubuntu Clear standard input buffer for C program in Linux

Hello friends! i am writing a code in which i take inputs (numbers) from user and count the total number of positive, negative and zeros entered. I need to clear my standard input buffer before scanf() command. My compiler is completely ignoring the fflush(stdin) command. its not even showing any error!. I am using Linux(ubunto) platform. Help!
Code:
#include<stdio.h>
int main()
{
	int pos=0,neg=0,zeros=0;
	float num;
	char ans='y';
	while(ans=='y')
	{
		printf("Enter a number : ");
		scanf("%f",&num);
		if(num>0)
		{
			pos++;
		}
		else if(num<0)
		{
			neg++;
		}		
		else
		{
			zeros++;
		}		
		
		printf("Wanna enter another number ? (y/n)\n");
		fflush(stdin);			
		scanf("%c",&ans);			
		if(ans=='n')
		{
		printf("positive number : %d \n Negative numbers : %d \n Zeros : %d",pos,neg,zeros);
		}

	}
return 0;
}


Last edited by Abhishek_kumar; 08-08-2014 at 02:27 PM..
# 2  
Old 08-08-2014
It certainly is showing error but you're not looking for it. That's what scanf()'s return value is for, it returns 0 if it reads no values, 1 if it found 1 value, 2 for 2, etc. Each %... code counts as one "value".

The buffering thing is a known issue with scanf(). It's a "feature" -- it stops scanning at the first bad character -- which is pretty useless if you're not building a compiler.

fflush should work, if you tell it which stream to flush, which you are not. But the proper way to avoid these buffer problems is to not use scanf().

You can still use sscanf though, which is just as good without the problems! It scans a string, and has no buffer to leave things in.

Here's the usual way to do it:

Code:
while(ans=='y')
{
        char line[512];
        float val;
        // Quit the loop if the file hits EOF
        if(fgets(line, 512, stdin) == NULL) break;

        // sscanf returns 1 if it reads one value, 2 if it found 2 values, etc.
        if(sscanf(line, "%f", &val) != 1)
        {
                fprintf(stderr, "'%s' is not a number\n", line);
                continue;  // Skip back to top of 'while'
        }

        // Quit the loop if the file hits EOF
        if(fgets(line, 512, stdin) == NULL) break;
        if(sscanf(line, "%c", &ans) != 1)
        {
                fprintf(stderr, "Couldn't read Y/N\n");
                continue;
        }
}


Last edited by Corona688; 08-08-2014 at 12:18 PM..
This User Gave Thanks to Corona688 For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Homework & Coursework Questions

Removing punctuations from file input or standard input

Just started learning Unix and received my first assignment recently. We haven't learned many commands and honestly, I'm stumped. I'd like to receive assistance/guidance/hints. 1. The problem statement, all variables and given/known data: How do I write a shell script that takes in a file or... (4 Replies)
Discussion started by: fozilla
4 Replies

2. UNIX for Advanced & Expert Users

Input buffer and READ

Hello everyone, Can someone please explain the input buffer behaviour for the read command in ksh93 on AIX? I have 'googled' for weeks now, and did not find a satisfactory answer or solution to my dilemma. I have the following code: STTY=$(stty -g) if ;then stty -echo -icanon time 0 min... (1 Reply)
Discussion started by: gio001
1 Replies

3. AIX

Need to clear the keyboard buffer

I'm running a ksh script that requires user interaction, and said users (myself among them) may get a little trigger happy and get ahead of ourselves and accidentally key in the wrong responses to future prompts in the script. Naturally, I'd like to prevent that, so how does one clear that... (0 Replies)
Discussion started by: Michael Mullig
0 Replies

4. HP-UX

How to clear keyboard buffer

Hi, How can i clear the command. Suppose using esc k i retrieved teh command, but for some reason I want to clear and type fresh one... how can i do that. thx (2 Replies)
Discussion started by: bang_dba
2 Replies

5. UNIX for Dummies Questions & Answers

invoking non-standard program in linux

I have a program R installed on Ubuntu under /usr/bin/R. I also have a different version installed under /home/user/R. I would like to invoke the locally installed program temporarily. How can I do this automatically by running a script and then switching to the default program? thanks, SM (2 Replies)
Discussion started by: smeme
2 Replies

6. Solaris

standard input

Please give me any example for standard input in Solaris. (6 Replies)
Discussion started by: karman0931
6 Replies

7. Programming

Clear Serial Port Buffer Using iclear, iflush

Hello, I am having trouble clearing the serial port buffer using the iclear and iflush commands. The code runs without errors being returned, but when I check the buffer again there is still data. The only way I have so far is to read until there is nothing left in the buffer. Shouldn't one... (1 Reply)
Discussion started by: sammy-e
1 Replies

8. Programming

How to clear the content of a pipe (STDIN) after it is written to another program?

PROGRAM A <-> PROGRAM B PROGRAM A sends data as STDIN ro PROGRAM B and when PROGRAM B is executed from PROGRAM A, it sends output back to PROGRAM A. This is implemented using 2 pipes (fd1 & fd2). The above process happens in a loop and during the second run, the previous data that had been... (10 Replies)
Discussion started by: vvaidyan
10 Replies

9. Shell Programming and Scripting

standard input

how can i redirect standard input? i dont remember :/, though could you redirec not from a command? i mean, to redirect always stdin and stout (1 Reply)
Discussion started by: Jariya
1 Replies

10. Programming

how to clear/clean mbufs (network buffer space)?

When I worked with client-server (socket) programming, I encountered "the socket error# 10055" which means "No buffer space available". This might be a symptom of one or more applications that didn't return system resources (like memory) properly. Temporary solution was to reboot the machine to... (7 Replies)
Discussion started by: dipti
7 Replies
Login or Register to Ask a Question