我如何知道用户是否在整数输入中输入了小数点?C 语言



我想从用户那里接收一个整数,我怎么知道他是否在不使用小数点(如 1 2 3 而不是 1.4 或 2.0 或 3.0(的情况下输入整数

通过测试每一步,您可以确保只输入一个整数。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
char str[100];
int num, index;
if(fgets(str, sizeof str, stdin) == NULL) {
// returns NULL if failed
printf("Bad string inputn");
}
else if(sscanf(str, "%d %n", &num, &index) != 1) {
// returns the number of converted items
// and sets index to the number of characters scanned
printf("Bad sscanf resultn");
}
else if(str[index] != 0) {
// checks that the string now ends (trailing whitespace was removed)
printf("Not an integer inputn");
}
else {
// success
printf("Number is %dn", num);
}
}

您可以将输入读取为字符串,然后扫描字符串以查找点。

#include <string.h>
#include <stdio.h>
int main (void) {
int i;
float f;
char input[256];
char dummy[256];
fgets(input, 256, stdin);
if(strchr(input, '.') != NULL) {
if(sscanf(input, "%f%s", &f, dummy) == 1) {
printf("%f is a floatn", f);
} else {
//error case
}
} else {
if(sscanf(input, "%d%s", &i, dummy) == 1) {
printf("%d is an integern", i);
} else {
// error case
}
}
return 0;
}

最新更新