Reading multiple lines of input with scanf
为类编写程序,仅限于scanf方法。程序接收可以接收任意数量的行作为输入。使用scanf接收多行输入时出现问题。
1 2 3 4 5 6 7 8 9
| #include <stdio.h>
int main (){
char s [100];
while(scanf("%[^\
]",s )==1){
printf("%s",s );
}
return 0;
} |
示例输入:
1 2
| Here is a line.
Here is another line. |
这是当前输出:
我希望我的输出与我的输入相同。使用scanf。
我认为您想要的是这样的东西(如果您真的只限于scanf):
1 2 3 4 5 6 7 8 9 10
| #include <stdio.h>
int main (){
char s [100];
while(scanf("%[^\
]%*c",s )==1){
printf("%s\
",s );
}
return 0;
} |
%* c基本上将抑制输入的最后一个字符。
来自man scanf
1 2 3 4 5
| An optional '*' assignment -suppression character :
scanf() reads input as directed by the conversion specification ,
but discards the input. No corresponding pointer argument is
required , and this specification is not included in the count of
successful assignments returned by scanf(). |
[编辑:根据克里斯·多德(Chris Dodd)的抨击删除了误导性答案:)]
-
1代表正确的第一个答案,-1代表完全错误且具有误导性的第二个答案。为什么人们不断推荐while(!feof)?一个肯定的指示器,表明程序员不知道自己在做什么。
-
如何消除多余的换行符(\\
)在输出的最后一行?
-
@ChrisDodd,是的,您是对的,我已经编辑了答案,以消除误导性的内容。
-
@Michael:好的,如果我需要读取整数或浮点数,则正则表达式是什么?
尝试此代码,然后使用Tab键作为分隔符
1 2 3 4 5 6 7 8
| #include <stdio.h>
int main (){
char s [100];
scanf("%[^\\t]",s );
printf("%s",s );
return 0;
} |
-
你能告诉我你用作输入的价值是什么
-
我认为这是因为内存问题,因为C不是一种内存安全的语言。
-
当我将数组大小增加到1024时,它可以很好地工作。您能解释一下为什么,以及如何选择正确的数组大小吗?
-
@PuneetPurohit:如果我需要一个制表符限制器,但是我需要读一个浮点数而不是一个字符串怎么办?
我会给你一个提示。
您需要重复scanf操作,直到达到" EOF"条件。
通常的方法是使用
构造。
- -1:while(!feof(..))几乎总是错误的,并且总是使最后一行错误,除非您进行英勇的努力来对其进行后期处理。
尝试这段代码。
它可以在符合C99标准的GCC编译器上正常工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include<stdio.h>
int main ()
{
int s [100];
printf("Enter multiple line strings\
");
scanf("%[^\
]s",s );
printf("Enterd String is\
");
printf("%s\
",s );
return 0;
} |