c语言 - 如何使代码在用户输入字符或字符串时说'invalid input'(验证)



我是c的新手,我只是想知道如果他们决定输入字符或胡言乱语,如何让我的代码说'无效输入'。

我的代码只是开尔文的简单摄氏度(我知道非常简单(,我只是在任何输入的数字上加 273。 我尝试使用isdidgit,但没有成功。

我的代码;

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int temp = 273;
int cel;
int cel2;
int choice;
switch (choice)
{
case 1:
printf("enter ce to conv to kel: ");
scanf("%ld", &cel);
cel2 = cel + temp;          
printf("%d in Celsuis is: %d Kelvin n", cel, cel2)

我接受所有反馈/改进, 谢谢 ~尼阿姆斯

目前,您的代码无法从无效输入中恢复。 也就是说,如果用户在出现提示时输入"a"scanf()将永远不会返回,因为它将等待以 10 为基数的整数值。

您需要做的是将输入读取为 C 字符串并处理:

char input[80];
do {
printf("enter ce to conv to kel: ");
scanf("%79[^n]n", input); // read until newline; toss newline
} while (input_is_bad(input)); // your function to validate input
cel = atoi(input); // atoi parses C-string, returning an int
cel2 = cel + temp;
printf("%d in Celsuis is: %d Kelvin n", cel, cel2);

在您自己的input_is_bad()函数中,您可以打印一条消息,指出输入无效。

您可以使用fgetsstrtol来实现此目的。请参阅以下代码:

#include<stdio.h>
#include <stdlib.h>
int main()
{
int temp = 273;
int cel;
int cel2;
int choice;
int flag;
char *p, str[100];
printf("enter ce to conv to kel: ");
while (fgets(str, sizeof(str), stdin)) {
cel = strtol(str, &p, 10); //number of base 10
if (p == str || *p != 'n') {
printf("Please enter an integer: ");
}
else break; //if input is integer then break the loop
}
//do your calculations here
return 0;
}

相关内容

最新更新