gpt4 book ai didi

C 程序获取有效输入

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

我想制作一个将千米转换为米的程序。但此外我想要一个条件,如果用户输入任何无效的数据类型而不是正数值,程序会重新强制用户输入有效值。仅使用循环和条件结构进行编程。输入应该通过scanf函数。

#include <stdio.h>
#include <conio.h>
main()
{
int a, b;
printf("Please Enter the Kilometers:");
scanf("%d", &a);
b=a*1000;
printf("%d kilometers are %d meters", a, b);
getch();
}

最佳答案

这看起来像一个硬件,所以我将给出一个输入所需行为的示例,但您将在实际代码中包含下面示例的逻辑。

你可以这样做:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

#define MAXINPUT 100

int main() {
char input[MAXINPUT] = "";
int length, i, ok;
do {
ok = 1;
scanf("%s", input);
length = strlen(input);
if (input <= 0) {
ok = 0;
printf("Entered input is not a positive number\n");
} else {
for (i = 0; i < length; i++) {
if (!isdigit(input[i])) {
printf("Entered input is not a number\n");
ok = 0;
}
}
}
} while (!ok);

printf("Given input is a positive number\n");
return 0;
}

如果用户输入的内容不是正数或不是数字(例如,当他输入字符时),该程序将使用户再次输入。我们使用名为 ok 的标志在循环结束时检查输入是否正确。

关于C 程序获取有效输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26667280/

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