繁体   English   中英

用户C编程的整数输入

[英]Integer input by user C programming

该程序用于验证用户输入的整数。 如果数据类型不正确或输入为空,则返回错误。 但只有一次。 我想改变这个程序以不断询问用户直到答案是好的。这是一个“一次性”程序,但我希望它可以用一段时间但它是无限的。

    #include <stdio.h>

    int main()
      {
    int num;
    char term;

    if(scanf("%d%c", &num, &term) != 2 || term != '\n')
    {
        printf("failure\n");
    }
    else 
    {
        printf("valid integer followed by enter key\n");
    }

    return 0;
    }

“......它工作正常,但我无法理解。你能解释一下吗?”

scanf() 函数是这段代码的核心。

scanf()返回成功转换的项目数。 在此示例中,程序尝试转换 2 个项目,因此检查 return is == 2将确认调用成功。 显然,编码器的意图似乎是验证是否捕获了数值和换行符。 对于这个简单的例子,这段代码就足够了,但是scanf()能够处理更多的. 与此同时, 可以说有更好的用户输入替代方案

让我试试:我已经 5 年没有接触过C++/C所以请原谅我的语法错误。

做时:

#include <stdio.h>

int main()
{
    int num;
    char term;
    
    do{
        user_input = scanf("%d%c", &num, &term)
        //Code for wrong input
     }
    while(user_input != 2 || term != '\n')
    //Code for right input

    return 0;
}

尽管:

#include <stdio.h>
    
int main()
{
    int num;
    char term;
  
    user_input = scanf("%d%c", &num, &term)
    while(user_input != 2 || term != '\n')
    {
        //Code for wrong input
        user_input = scanf("%d%c", &num, &term)  //In while loop you've to take input again
    }
    //Code for right input
    return 0;
}

暂无
暂无

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

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