【发布时间】: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读取一行。