如何使用scanf()获取任意数量的整数?

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

例如

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

另一个例子:

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

我该怎么做??

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

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

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

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

这种方式最好有一个循环。
当用户没有输入“\ 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*/ } 

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

 #include  #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