gpt4 book ai didi

c - 使用 scanf 仅接受输入的数值

转载 作者:行者123 更新时间:2023-12-04 02:47:34 25 4
gpt4 key购买 nike

如何确保用户只输入数值而不是字母数字或任何其他字符?还需要寻找什么来为不正确的输入插入错误消息?

#include<stdio.h>

int main()
{
int a, b, c;


printf("Enter first number to add\n");
scanf("%d",&a);

printf("Enter second number to add\n");
scanf("%d",&b);

c = a + b;

printf("Sum of entered numbers = %d\n",c);

return 0;
}

最佳答案

如果您真的想处理可能具有敌意的用户输入,请使用单独的函数来获取数字。

允许
- 前导空格:“123”
- 尾随空格:“123”
- 前导零:“000000000000000000000000000000000123”
- 错误输入后重新扫描。
捕获以下错误
- 无输入:“”
- 号码后的额外文字:“123 abc”
- 号码前的文字:“abc 123”
- 拆分号码:“123 456”
- 溢出/下溢:“12345678901234567890”
- 其他:“--123”
重新提示无效输入。

#include <errno.h>
#include <stdio.h>
#include <stddef.h>

int GetInteger(const char *prompt, int *i) {
int Invalid = 0;
int EndIndex;
char buffer[100];
do {
if (Invalid)
fputs("Invalid input, try again.\n", stdout);
Invalid = 1;
fputs(prompt, stdout);
if (NULL == fgets(buffer, sizeof(buffer), stdin))
return 1;
errno = 0;
} while ((1 != sscanf(buffer, "%d %n", i, &EndIndex)) || buffer[EndIndex] || errno);
return 0;
}

int main() {
int a, b, c;
if (GetInteger("Enter first number to add\n", &a)) {
; // End of file or I/O error (rare)
}
if (GetInteger("Enter second number to add\n", &b)) {
; // End of file or I/O error (rare)
}
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}

顺便说一句,你不应该 printf("Enter first number to add\n")。请改用 fputs()。考虑一下如果字符串中有 % 会发生什么。

关于c - 使用 scanf 仅接受输入的数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18584302/

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