scanf() 用于格式化输入(这就是为什么它的名称中有一个 f ^^)。在这里,您的输入未格式化,因此您必须执行其他操作。
最好的方法是使用fgets() 获取用户输入,然后检查内容。如前所述,strtol() 是此任务的专用函数:您尝试将字符串转换为数字,然后查看转换是否成功...。
这是一个例子:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#define SIZE 1024
void convert() {
// Get user input
char buffer[SIZE] = {0};
printf("Enter number: ");
char* result = fgets(buffer, SIZE, stdin);
assert(result != NULL);
printf("User input = %s\n", buffer);
// Convert
char* end = NULL;
long int value = strtol(buffer, &end, 10);
if (buffer[0] == '\n') {
// The user didn't input anything
// and just hit 'enter' kit
puts("Nothing to convert");
}
else if(*end == '\n') {
// Assuming that 'buffer' was big enough to get all characters,
// then the last character in 'buffer' is '\n'.
// Because we want all characters except '\n' to be converted
// we have to check that 'strtol()' has reached this character.
printf("Conversion with success: %ld\n", value);
} else {
printf("Conversion failed. First invalid character: %c\n", *end);
}
}
int main() {
while(1) convert();
}
如果你真的想要int 而不是long int,那么你就得花点小心思了。我的第一个想法是做这样的事情:
// Fits in integer?
int valueInt = value;
// some bits will be lost if 'value' doesn't fit in an integer
// hence the value will be lost
if (valueInt == value) {
printf("Great: %ld == %d\n", value, valueInt);
} else {
printf("Sorry: %ld != %d\n", value, valueInt);
}