c - 当用户输入字符或字符串时如何使代码显示“无效输入”(验证)
问题描述
我是 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()
函数中,您可以打印一条消息,说明输入无效。
推荐阅读
- java - org.hibernate.id.IdentifierGenerationException: 试图从空的一对一属性分配 id (hibernate+postgres)
- swift - 如何执行一个又一个功能?
- ios - 命令 PhaseScriptExecution 在离子电容器应用程序中因非零退出代码而失败
- reporting-services - SSRS 在将报告发送到打印机之前计算报告的总长度
- windows - application.exe 已触发断点
- r - 将向量“日期”合并到 R 中的数据框中
- sql - 将页眉和页脚添加到 SQL 输出
- python-3.x - 从 ImageDataGenerator 重塑图像
- c - 按值传递结构时出现意外的汇编输出
- python - 如何让 BeautifulSoup 获得多个课程?