如果您不想使用scanf,您有几个选择:
您可以使用fgets 和strtol(用于整数输入)或strtod(用于浮点输入)的组合。示例(未经测试):
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
...
char buf[12]; // 10 digits, plus sign, plus terminator
char *chk; // points to first character *not* converted by strtol
if ( !fgets( buf, sizeof buf, stdin ) )
{
fprintf( stderr, "Error on input\n" );
return EXIT_FAILURE;
}
long value = strtol( buf, &chk, 10 ); // 10 means we expect decimal input
if ( !isspace( *chk ) && *chk != 0 )
{
fprintf( stderr, "Found non-decimal character %c in %s\n", *chk, buf );
fprintf( stderr, "value may have been truncated\n" );
}
printf( "Input value is %ld\n", value );
您可以使用getchar 读取单个字符,使用isdigit 检查每个字符,然后手动构建值。示例(也未经测试):
#include <stdio.h>
#include <ctype.h>
...
int value = 0;
for ( int c = getchar(); isdigit( c ); c = getchar() ) // again, assumes decimal input
{
value *= 10;
value += c - '0';
}
printf( "Value is %d\n", value );