如何读取的变量从scanf的(通过空间或新行分开)
问题描述:
我想要写一个程序,读取正整数值从stdin任意数量(由新线或空格分隔)不确定数目,并输出相应的#的新行数。例如:如何读取的变量从scanf的(通过空间或新行分开)
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;
}
它适用于前两个例子完全正常,但我应该怎么做的第三个,当输入是在不同的线路?我的程序只在第三个例子中输出“#”,这意味着它只读取输出的第一行。
答
你的代码是读一个线路输入号码,然后printf
#
。你的号码只需拨打fgets
一次,所以它只能读取input.You的第一行可以使用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
然后sscanf
,您可以在while
循环中使用fscanf/scanf
。
int main(){
int a;
while (fscanf(stdin, "%d", &a) == 1)
{
while(a-- > 0){
printf("*");
}
printf("\n");
}
return 0;
}
内部环路'的scanf( “%d”,%×);'将很好地工作。只要遇到'fgets'中的新行就会返回。否则,要逐行阅读,在'while'循环中放置'fgets'。 – ameyCU
你可以多次调用'fgets'? 'fgets'只读一行。 – immibis