gpt4 book ai didi

c - 如何只允许在数组中输入数字?

转载 作者:行者123 更新时间:2023-11-30 14:34:31 25 4
gpt4 key购买 nike

所以我正在尝试编写一个程序,从用户那里接收 10 位数字的电话号码。它的长度只能是 10 个字符。它只能由数字组成。输入字母字符或特殊字符将给出错误消息。我尝试过使用 isdigits() 函数,但这似乎不起作用。到目前为止,这是我的代码。

在不使用 isdigits() 的情况下,还有其他方法可以做到这一点吗?

#include <stdio.h>
#include <string.h>
#include <ctype.h>
void clearKeyboard(void);

int main (void)
{
char phoneNum[11];
int needInput = 1;
int i;
int flagBad = 0;
while (needInput == 1) {
scanf_s("%10s", phoneNum);
clearKeyboard();
// (String Length Function: validate entry of 10 characters)
if (strlen(phoneNum) == 10) {
needInput = 0;
for (i = 0; i < 10; i++) {
if (isdigits(phoneNum[i] == 0)) {
flagBad = 1;
}
}
if (flagBad == 1) {
needInput = 1;
printf("Enter a 10-digit phone number: ");
}
}
else needInput == 0;
}
printf("Successful");
return 0;
}

void clearKeyboard(void)
{
while (getchar() != '\n'); // empty execution code block on purpose
}

最佳答案

scanf_s("%10s",phoneNum); 由于缺少参数而失败。查看您的 scanf_s() 文档。

<小时/>

我不推荐scanf_s()。相反,应避免将用户 I/O 与输入验证混合在一起。获取输入,然后验证它。

   char buf[80]; // Be generous.
if (fgets(buf, sizeof buf, stdin)) {
buf[strcspn(buf, "\n")] = '\0'; // Lop off potential \n
// OK we have the input, now validate.

char phoneNum[11];
int n = 0;
// Use sscanf, isdigit, or ...
if (sscanf(buf, "%10[0-9]", phoneNum, &n) == 1 && n == 10 && buf[n]==0) {
puts("Success");
} else {
printf("Bad input <%s>\n", buf);
}
<小时/>

"%10[0-9]%n",phoneNum, &n --> 将 1 到 10 位数字扫描到 phoneNum[] 中并附加 '\0'。将扫描偏移保存到n

关于c - 如何只允许在数组中输入数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58945383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com