【问题标题】:What can I use for taking integer input instead of scanf in C?我可以使用什么来获取整数输入而不是 C 中的 scanf?
【发布时间】:2020-07-29 06:34:53
【问题描述】:

我正在学习 C。我目前正在使用 CLion IDE 来练习 C。我之前使用过 codeblocksvs code 并且还可以。但是 Clion 对scanf() 显示警告。有什么东西可以用来代替 scanf 来获取 integer、float 和 double 之类的输入吗?

如果我知道,将非常感激。

【问题讨论】:

  • 请分享警告是什么。

标签: c scanf user-input


【解决方案1】:

不要将scanf() 用于用户输入,它有几个缺点。

请改用fgets()

这是关于“为什么”部分的nice read(场外资源)。

【讨论】:

    【解决方案2】:

    使用 fgets() 。 这是 CLion IDE 中用于 scanf 功能的错误。 如果您能说出您收到的警告是什么,将不胜感激。

    【讨论】:

    • 这应该是一条评论
    【解决方案3】:

    如果您不想使用scanf,您有几个选择: 您可以使用fgetsstrtol(用于整数输入)或strtod(用于浮点输入)的组合。示例(未经测试):

    #include <stdio.h>
    #include <stdlib.h>
    #include <ctype.h>
    ...
    char buf[12]; // 10 digits, plus sign, plus terminator
    char *chk; // points to first character *not* converted by strtol
    
    if ( !fgets( buf, sizeof buf, stdin ) )
    {
      fprintf( stderr, "Error on input\n" );
      return EXIT_FAILURE;
    }
    
    long value = strtol( buf, &chk, 10 ); // 10 means we expect decimal input
    if ( !isspace( *chk ) && *chk != 0 )
    {
      fprintf( stderr, "Found non-decimal character %c in %s\n", *chk, buf );
      fprintf( stderr, "value may have been truncated\n" );
    }
    printf( "Input value is %ld\n", value );
    

    您可以使用getchar 读取单个字符,使用isdigit 检查每个字符,然后手动构建值。示例(也未经测试):

    #include <stdio.h>
    #include <ctype.h>
    ...
    int value = 0;
    for ( int c = getchar(); isdigit( c ); c = getchar() ) // again, assumes decimal input
    {
      value *= 10;
      value += c - '0';
    }
    printf( "Value is %d\n", value );
    

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2022-11-16
      相关资源
      最近更新 更多