如何读取的变量从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; 
} 

它适用于前两个例子完全正常,但我应该怎么做的第三个,当输入是在不同的线路?我的程序只在第三个例子中输出“#”,这意味着它只读取输出的第一行。

+1

内部环路'的scanf( “%d”,%×);'将很好地工作。只要遇到'fgets'中的新行就会返回。否则,要逐行阅读,在'while'循环中放置'fgets'。 – ameyCU

+0

你可以多次调用'fgets'? 'fgets'只读一行。 – immibis

你的代码是读一个线路输入号码,然后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只是为了学习,它在实际的程序中没有什么用处,所以不要花太多时间在它上面。

+0

'fgets'将在错误或EOF中返回NULL,所以不用与'0'比较就使用'NULL'。而不是比较'sscanf'的返回和'EOF',你可以使用它正确匹配的参数的数量。所以它可能是'sscanf(...)== 2;' – ameyCU

+0

@ameyCU“它可能是'sscanf(...)== 1;'”'“%n”'不会影响返回值。 – chux

+0

虽然OP提到了数字输入,但是非数字输入,这个答案会表现出未定义的行为(UB):(在iniitalized之前使用的'j')。建议'sscanf(buffer + i,“%d%n”,&a,&j)== 1' – chux

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

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