C语言 使用 scanf 读取多行输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14494309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading multiple lines of input with scanf
提问by John
Writing a program for class, restricted to only scanf method. Program receives can receive any number of lines as input. Trouble with receiving input of multiple lines with scanf.
为类编写程序,仅限于 scanf 方法。程序接收可以接收任意数量的行作为输入。使用 scanf 接收多行输入时出现问题。
#include <stdio.h>
int main(){
char s[100];
while(scanf("%[^\n]",s)==1){
printf("%s",s);
}
return 0;
}
Example input:
示例输入:
Here is a line.
Here is another line.
This is the current output:
这是当前的输出:
Here is a line.
I want my output to be identical to my input. Using scanf.
我希望我的输出与我的输入相同。使用 scanf。
回答by Michael
I think what you want is something like this (if you're really limited only to scanf):
我认为你想要的是这样的(如果你真的仅限于 scanf):
#include <stdio.h>
int main(){
char s[100];
while(scanf("%[^\n]%*c",s)==1){
printf("%s\n",s);
}
return 0;
}
The %*c is basically going to suppress the last character of input.
%*c 基本上会抑制输入的最后一个字符。
From man scanf
从 man scanf
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().
[ Edit: removed misleading answer as per Chris Dodd's bashing :) ]
[编辑:根据克里斯·多德的抨击删除了误导性答案:)]
回答by Puneet Purohit
try this code and use tab key as delimeter
试试这个代码并使用 tab 键作为分隔符
#include <stdio.h>
int main(){
char s[100];
scanf("%[^\t]",s);
printf("%s",s);
return 0;
}
回答by Thrill Science
I'll give you a hint.
我给你一个提示。
You need to repeat the scanf operation until an "EOF" condition is reached.
您需要重复 scanf 操作,直到达到“EOF”条件。
The way that's usually done is with the
通常的做法是使用
while (!feof(stdin)) {
}
construct.
构造。
回答by Sudhanshu Agrahari
Try this piece of code.. It works as desired on a GCC compiler with C99 standards..
试试这段代码..它在具有 C99 标准的 GCC 编译器上按需要工作..
#include<stdio.h>
int main()
{
int s[100];
printf("Enter multiple line strings\n");
scanf("%[^\r]s",s);
printf("Enterd String is\n");
printf("%s\n",s);
return 0;
}

