Does anyone know what is the best function to use if you want to read user input and not have the return key carry over? Everytime I write something that reads in two things, the second read in always ends up being '\n' because the return key carries over to the next input.

Does anyone know what is the best function to use if you want to read user input and not have the return key carry over? Everytime I write something that reads in two things, the second read in always ends up being '\n' because the return key carries over to the next input.

I think you can use getc()

There are a few things you can try out. For eg. you can accept everything as string from the user and parse it to get out the data which you require using [search]sscanf( )[/search]

int main( )
{
    char buffer[BUFSIZ] = { '\0' } ;
    char name[8] = { '\0' } ;
    fgets( buffer, BUFSIZ, stdin ) ;
    sscanf( buffer, "%s", name ) ;
    printf( "The name is %s", name ) ;
    getchar( ) ;
}

Of if you still want to use scanf( ) and write programs that way you can just put getchar( ) after each scanf( ) to take care of the stray '\n'.

int i = 0 ;
char name[10] ;
scanf( "%d", &i ) ;
getchar( ) ;
scanf( "%s", name ) ;
getchar( ) ;

Hope it helped, bye.

Does anyone know what is the best function to use if you want to read user input and not have the return key carry over? Everytime I write something that reads in two things, the second read in always ends up being '\n' because the return key carries over to the next input.

It actually depends on what you're reading and how. Some functions leave the \n in the read buffer, others do not. Some functions ignore \n for certain data types, but not for others. Give us an idea what you are reading and how.

Since you didn't specify, my guess is you're using scanf() to read numbers and characters. This has always been a problem. SOS has a very workable solution if this is the case.

This article has been dead for over six months. Start a new discussion instead.