Ooooo fun with pointers.
Code:
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
const char *specifier[] = { "%c", "%d", "%f", "%s" };
size_t size[] = { 1, sizeof( int ), sizeof( float ), BUFSIZ };
int x;
void *data = NULL;
printf(
"1) Read a single character.\n"
"2) Read a single integer.\n"
"3) Read a floating point number.\n"
"4) Readin a string.\n\n"
"Your choice: "
);
x = getchar();
if( x < '1' || x > '4' )
return !!printf( "Next time try following the rules.\n" );
x -= '1';
while( getchar() != '\n' );
if( (data = malloc( size[ x ] )) )
{
printf( "Enter your data now: " );
fflush( stdout );
if( scanf( specifier[ x ], data ) == 1 )
{
printf( "You entered \'" );
switch( x )
{
case 0: printf( specifier[ x ], *((char*)data) ); break;
case 1: printf( specifier[ x ], *((int*)data) ); break;
case 2: printf( specifier[ x ], *((float*)data) ); break;
case 3: printf( specifier[ x ], (char*)data ); break;
}
printf( "\'!\n" );
}
free( data );
}
return 0;
}
There's a fun example.
Quzah.