我正在编写一个接受来自 stdin
的输入的小程序并检查它是否包含数字。问题是它只适用于 scanf()
而不是 fgets
(我想避免使用 scanf
)。
为此我使用了 isDigit
来自 <ctype.h>
的函数以及检查数组中每个字符的以下函数:
int isNumeric(const char *buf) {
for(size_t i = 0; i < strlen(buf); i++)
if(isDigit(buf[i]) == 0)
return false;
return true;
}
这是驱动代码:
// This does not works
int main(void) {
char c[256];
fgets(c, sizeof(c), stdin);
if(isNumeric(c))
puts("Is numeric");
else
puts("Not numeric");
}
// ####################
// This works
int main(void) {
char c[256];
scanf("%s", c);
if(isNumeric(c))
puts("Is numeric");
else
puts("Not numeric");
}
显然,预期的输出应该是“是数字”。
我对 fgets
做错了什么?
最佳答案
Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.
因此,在将字符串提供给 isNumeric
之前,您需要修剪尾随的 eol 字符。
关于c - 为什么这个 isNumeric 函数不能与 fgets 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57769486/