I'm being taught to use fflush( stdin ) to clean the buffer, use gets to read strings, etc, etc
But it seems these are not the proper methods to read input from keyboard.
I've made this functions in order to read the input based on this useful recommendations.
So I would like to know if there is any way to improve them, if you see any kind of problem with them or if something it's already in the c library and therefore it's not necessary a custom function.
Mostly because I will be using it in all my future c programs.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getCharacter( char * );
int getNumber ( int* );
void getString( char* string );
int main( void )
{
int number;
char character;
char string[ BUFSIZ ];
printf( "Character: " );
getCharacter( &character );
printf( "Number: " );
getNumber( &number );
printf( "String: " );
getString( string );
printf( "Character -> %c\n", character );
printf( "Number -> %d\n", number );
printf( "String -> %s\n", string );
system( "pause" );
}
int getCharacter( char* c )
{
char buffer[ BUFSIZ ];
fgets(buffer, sizeof( buffer ), stdin);
return sscanf( buffer, "%c", c);
}
int getNumber ( int* num )
{
char buffer[ BUFSIZ ];
fgets(buffer, sizeof( buffer ), stdin);
return sscanf( buffer, "%d", num);
}
void getString( char* string )
{
char buffer[ BUFSIZ ];
char *p;
fgets( buffer, sizeof( buffer ), stdin );
if ((p = strchr( buffer, '\n')) != NULL)
*p = '\0';
strcpy( string, buffer );
}