使用scanf读取多行输入

为类编写程序,仅限于scanf方法。 程序接收可以接收任意数量的行作为输入。 使用scanf接收多行输入时出现问题。

#include  int main(){ char s[100]; while(scanf("%[^\n]",s)==1){ printf("%s",s); } return 0; } 

示例输入:

 Here is a line. Here is another line. 

这是当前的输出:

 Here is a line. 

我希望我的输出与我的输入相同。 使用scanf。

尝试此代码并使用tab键作为分隔符

 #include  int main(){ char s[100]; scanf("%[^\t]",s); printf("%s",s); return 0; } 

我想你想要的是这样的(如果你真的只限于scanf):

 #include  int main(){ char s[100]; while(scanf("%[^\n]%*c",s)==1){ printf("%s\n",s); } return 0; } 

%* c基本上会抑制输入的最后一个字符。

来自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(). 

[编辑:根据克里斯多德的抨击删除误导性答案:)]

我会给你一个提示。

您需要重复scanf操作,直到达到“EOF”条件。

通常采用的方式是

 while (!feof(stdin)) { } 

构造。

试试这段代码..它可以在带有C99标准的GCC编译器上运行。

 #include 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; }