关于C#:使用scanf读取多行输入


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.

这是当前输出:

1
Here is a 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)的抨击删除了误导性答案:)]


尝试此代码,然后使用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;
}


我会给你一个提示。

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

通常的方法是使用

1
2
while (!feof(stdin)) {
}

构造。


尝试这段代码。
它可以在符合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;
}