简体   繁体   English

如何检查用户是否输入了输入

[英]How to check if user entered an input or not

Im using this code to allow the use to enter a numerical value for the variable: 我使用此代码来允许为变量输入数值:

float day;
printf("Day?: ");
scanf("%f",&day);

how can i make the program produce an error message if the user did not enter ANY value for "Day"?? 如果用户未为“天”输入任何值,我如何使程序产生错误消息?

Try this: 尝试这个:

if(scanf("%f",&day) != 1)  
    printf("Error"); 

Use fgets()/sscanf() 使用fgets()/sscanf()

char buf[100];
fgets(buf, sizeof(buf), stdin);
if (sscanf(buf, "%f", &day) != 1) {
   if (buf[0] == '\n') 
     HandleNothingInput(); 
   else 
     HandleBadInput(); 
   }
}

fgets() typically reads until a Enter or '\\n' is entered. fgets()通常读取直到输入Enter'\\n' By using sscanf() to parse the buffer, empty inputs ("user did not enter ANY value"), bad input ("abc") are readily detected as the result of scanf() will be 0. 通过使用sscanf()解析缓冲区,很容易检测到空输入(“用户未输入ANY值”),错误输入(“ abc”),因为scanf()的结果将为0。


Alternatives: If you want to insure no additional data is entered, one could use a sentinel: 替代方法:如果要确保没有输入其他数据,可以使用一个哨兵:

int ch;     
if (sscanf(buf, "%f %c", &day, &ch) != 1) {

atof() is another approach. atof()是另一种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM