【问题标题】:How to read an indefinite number of variables from scanf (separated by space or new lines)如何从 scanf 中读取不定数量的变量(以空格或换行符分隔)
【发布时间】:2024-01-07 05:39:01
【问题描述】:

我想编写一个程序,从标准输入读取任意数量的正整数值(由新行或空格分隔)并在新行中输出相应数量的#。示例:

Input:
5 4 3 2 1

Output:
#####
####
###
##
#

Input:
16
0
4
12

Output:
################

####
############

Input:
1 1 3 
2 1

Output:
#
#
###
##
#

我的代码:

#include <stdio.h>

int main(){
    char buffer[1000];
    if (fgets(buffer, sizeof(buffer), stdin) != 0){
        int i,j,a;
        for(i=0; sscanf(buffer+i,"%d%n",&a,&j)!=EOF; i+=j){
            while(a-->0){
                printf("*");
            }
            printf("\n");
        }
    }
    return 0;
}

前两个示例运行良好,但是当输入位于不同行时,我应该如何处理第三个示例?我的程序在第三个例子中只输出“#”,意思是它只读取输出的第一行。

【问题讨论】:

  • 在循环内scanf("%d",%x); 可以正常工作。只要遇到fgets 中的新行,就会返回。否则逐行读取将fgets 放入while 循环中。
  • 您可以多次致电fgets 吗? fgets 读取一行。

标签: c scanf


【解决方案1】:

你的代码是读取一行输入数字,然后printf#的数字。你只需调用一次fgets,所以它只读取输入的第一行。你可以使用while

#include <stdio.h>
int main(){
    char buffer[1000];
    while (fgets(buffer, sizeof(buffer), stdin) != 0){
        int i,j,a;
        for(i=0; sscanf(buffer+i,"%d%n",&a,&j)!=EOF; i+=j){
            while(a-->0){
                printf("#");
            }
            printf("\n");
        }
    }
    return 0;
}

顺便说一句,scanf只是学习用的,在实际程序中用处不大,所以不要花太多时间。

【讨论】:

  • fgets 将在错误或 EOF 时返回 NULL,因此不要与 0 进行比较,而是使用 NULL。而不是将sscanf 的返回值与EOF 进行比较,您可以使用它正确匹配的参数数量。所以可能是sscanf(...) == 2;
  • @ameyCU "可能是sscanf(...) == 1;" "%n" 对返回值没有贡献。
  • 虽然 OP 提到了数字输入,但使用非数字导入此答案将表现出未定义的行为 (UB):(j 在初始化之前使用)。推荐sscanf(buffer+i,"%d %n",&amp;a,&amp;j) == 1
【解决方案2】:

您可以在while 循环中使用fscanf/scanf,而不是使用fgets 然后sscanf

int main(){
    int a;
    while ( fscanf(stdin, "%d", &a) == 1 )
    {
       while(a-- > 0){
          printf("*");
       }
       printf("\n");
    }
    return 0;
}

【讨论】:

    最近更新 更多