【问题标题】:How do I use scanf() to take an arbitrary amount of integers? [closed]如何使用 scanf() 获取任意数量的整数? [关闭]
【发布时间】:2012-08-07 05:23:32
【问题描述】:

程序将任意数量的整数作为输入,并给出该整数和该数量星的输出。

例如

In: 1 2 3
Out: 
1 | *
2 | **
3 | ***

另一个例子:

In: 2 5 6 8
Out:
2 | **
5 | *****
6 | ******
8 | ********

我该怎么做??

顺便说一句,业余 C 程序员

以及如何在 Stack Overflow 问题格式的行之间添加单行空格“\n”

【问题讨论】:

  • 在“\n”的行尾使用
    标签
  • 你应该看看stackoverflow.com/questions/3764014/…(读到文件结束)
  • 如果你想成为一名优秀的程序员,你必须阅读书籍并使用搜索!
  • 读取输入、标记、解析并打印。 fgets 和 strtoul 应该可以。
  • 我已经学习 C 两个星期了,所以我很菜鸟!

标签: c


【解决方案1】:

要从一行中读取数字,您可以:

#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;
}

【讨论】:

  • 永远不要使用gets();它本质上是不安全的,已从语言中删除。
  • 哎呀...现在改为 fgets.. XD ...我的道歉
  • +1 用于正确使用 --&gt; 运算符。
【解决方案2】:

这种方式最好有一个循环。
虽然用户尚未输入 "\n",但您的程序应该能够将它们视为整数。当然,您也可以添加一些其他检查。

像这样:

int number = 0;
char c = '';
while(c != '\n'){
    getch(c);
    scanf("%d", &number);
    /*Do your star thing or add this number to an array for the later consideration*/
}


这尚未经过全面测试,您可能需要进行一些更改。

【讨论】:

    【解决方案3】:
    #include <stdio.h>
    
    #define SIZE 8
    
    int input_numbers(int numbers[]){
        int i=0,read_count;
        char ch;
    
        printf("In: ");
        while(EOF!=(read_count=scanf("%d%c", &numbers[i], &ch))){
            if(read_count==2)
                ++i;
            if(i==SIZE){
                fprintf(stderr, "Numeric number has reached the Max load.\n");
                return i;
            }
            if(ch == '\n')
                break;
        }
        return i;
    }
    
    void output_numbers(int numbers[], int size){
        int i,j;
        printf("Out:\n");
        for(i=0;i<size;++i){
            printf("%d | ", numbers[i]);
            for(j=0;j<numbers[i];++j){
                printf("*");
            }
            printf("\n");
        }
    }
    
    int main(void){
        int numbers[SIZE];
        int n;
    
        n=input_numbers(numbers);
        output_numbers(numbers, n);
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 2021-11-27
      • 1970-01-01
      • 2022-01-09
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多