使用scanf读取多行输入

时间:2013-01-24 05:01:56

标签: c

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

#include <stdio.h>
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。

4 个答案:

答案 0 :(得分:7)

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

#include <stdio.h>
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().

[编辑:根据Chris Dodd的抨击删除误导性答案:)]

答案 1 :(得分:5)

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

#include <stdio.h>
int main(){
    char s[100];
    scanf("%[^\t]",s);
    printf("%s",s);

    return 0;
}

答案 2 :(得分:1)

我会给你一个提示。

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

通常采用

的方式
while (!feof(stdin)) {
}

构造

答案 3 :(得分:0)

试试这段代码.. 它可以在具有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;
}
相关问题