user1242967
user1242967

Reputation: 1290

How to check if there are some some characters left in stdin after scanf?

scanf("%9s", line);

I read a line from stdin (max 9 symbols) and after that I want to check if I read all the characters from user input. Is there any elegant way to do it?

Upvotes: 4

Views: 7840

Answers (3)

Johannes
Johannes

Reputation: 6707

You could read the data into a bigger string first and afterwards get its length. At some point you want to just get rid of whatever is left on the input buffer. To do that you can use fflush on some systems and fpurge on all the others.

Here is some sample code that you could use to fill up a big buffer and just purge the rest. The cleaning function will remove the final newline or end the string early if any special characters are in it.

void userInput( char * str, int size );
void get( char * str, int size );  
void clean( char * str, int size );  
void flush( void );

void userInput( char * str, int size )
{
    get( str, size );
    clean( str, size );   
    flush();
}

void get( char * str, int size )
{
    memset( str, 0, size );
    fgets ( str, size, stdin );
}

void clean( char * str, int size )
{
    char * c;   
    str [size -1] = 0;
    c = str;
    while( *c >= ' ' || *c < 0 ) ++c;
    *c = 0;
}

void flush( void )
{
    //the ifdef approach does not work in reality.
    //this is a pseudo case for your benefit.
    #ifdef fpurge 
        fpurge(stdin);
    #else
        fflush(stdin);
    #endif
}

Upvotes: 0

chux
chux

Reputation: 153417

Recommend separating human input from parsing. Folks enter the most unexpected characters. and invariable I find it easier to correctly handle these issues separately.

Read in the line (this I put in its own function)

char buf[1024];
char *retval;
retval = fgets(buf, sizeof(buf), stdin);
// if I/O trouble reading ...
if (!retval) {
  handle error
} 
// if End-of-line missing (as buffer was filled) ...
if (!strchr(buf, '\n')) {
  handle error
} 
// Toss '\n'
buf[strlen(buf) - 1] = '\0';

Then parse the data

sscanf(buf, "%9s", line); 
if (strlen(buf) > 9) {
  // You have extra data
  }

Upvotes: 1

Soumik Das
Soumik Das

Reputation: 376

feof() will allow you to check if the stdin buffer is empty. Else if you want to go further and check the contents ...use something like this..

while ( fgets(buf,BUFSIZ,stdin) != NULL ) 
  {     printf("%s",buf); }

Here buf will be the array/string to hold BUFSIZ bytes of data

Upvotes: 3

Related Questions