我是 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
目前,您的代码无法从无效输入中恢复。也就是说,如果用户"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()
函数中,您可以打印一条消息,指出输入无效。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句