首页 > 解决方案 > 当用户输入字符或字符串时如何使代码显示“无效输入”(验证)

问题描述

我是 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)

我接受所有反馈/改进,谢谢~Neamus

标签: cvalidation

解决方案


目前,您的代码无法从无效输入中恢复。也就是说,如果用户"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()函数中,您可以打印一条消息,说明输入无效。


推荐阅读