【问题标题】:How can I take integer input dynamically and have the loop terminate on pressing enter?如何动态获取整数输入并在按 Enter 时终止循环?
【发布时间】:2019-12-15 06:52:55
【问题描述】:

我需要动态输入整数,并在用户按下回车后立即终止。当我将字符作为输入时,我从来没有遇到过任何问题,因为我可以轻松检查换行符并且每个字符都是一个字符。但是在这里,我不能只输入一个 char 并减去 '0',因为当我输入 10 时,char 值是 1,然后是 0。

这是我正在使用的一段代码:

int no;
while (scanf_s(" %d", &no) == 1)
    {
        printf("%d ", no);
    }

这是我用于输入字符的另一段代码,这也适用于个位数整数:

char no;
while ((no=getchar()) != EOF && no != '\n')
    {
        printf(" %d ", no - '0');
    }

按下回车键时 scanf 循环不会终止,但它确实正确地接受了所有输入。然而,getchar 循环正确终止,但只存储 1 位整数。

如何在空行用户输入处终止整数输入?

【问题讨论】:

  • 很简单:不要使用scanf。它是根据基于流的输入定义的;它没有线条的概念。如果要读取和解释输入行,请使用fgets 将行读取为字符串,然后处理字符串。 (这样做还可以避免scanf 的无数其他困难。)
  • 当您将%dscanf 一起使用时,这意味着“跳过前导空格,然后读取由一位或多位数字组成的整数”。没有办法关闭“跳过前导空格”部分,这是导致您的问题的原因。
  • 您可以做的一件事(如果您想坚持使用scanf)是将提示从“输入数字,以空行终止”更改为“输入数字,以任何非数字字符终止” ”。如果用户输入 x 或其他内容,导致 scanf 失败并返回 0。

标签: c loops input fgets strtol


【解决方案1】:

您可以使用标准函数fgets 将输入读入字符数组,然后使用标准函数strtol 提取数字。

这是一个演示程序

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int is_empty( const char *s )
{
    return s[strspn( s, " \t" )] == '\n';   
}

int main(void) 
{
    enum { N = 100 };
    char line[N];

    while ( fgets( line, N, stdin ) && !is_empty( line ) )
    {
        char *endptr;

        for ( const char *p = line; *p != '\n'; p = endptr )
        {
            int num = strtol( p, &endptr, 10 );
            printf( "%d ", num );

        }
    }

    return 0;
}

如果要输入以下几行

1
2 3
4 5 6
7 8
9

(最后一行是空的,是用户刚按回车)

那么输出会是这样的

1 2 3 4 5 6 7 8 9

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多