如何使用scanf(而不是fgets)读取文本行?
我需要编写一个程序,从输入中读入可能多行的文本。程序需要使用scanf和printf,并且没有其他库函数,因此没有fgets、getchar或其他任何函数如何使用scanf(而不是fgets)读取文本行?,c,scanf,C,Scanf,我需要编写一个程序,从输入中读入可能多行的文本。程序需要使用scanf和printf,并且没有其他库函数,因此没有fgets、getchar或其他任何函数 我知道你可以用以下一行来阅读: scanf("%[^\n]s", text); 但这会留下一个\n,它: 需要在名为text的数组末尾添加 及 b阻止输入的其余行被读入 这是我到目前为止的代码 void print_line() { int i = 0; while(i < 12) { char inpu
我知道你可以用以下一行来阅读:
scanf("%[^\n]s", text);
但这会留下一个\n,它:
需要在名为text的数组末尾添加
及
b阻止输入的其余行被读入
这是我到目前为止的代码
void print_line()
{
int i = 0;
while(i < 12)
{
char input_text[100];
/*printf("Input text here: ");*/
/*scanf("%[^\n]s\n", input_text);*/
/*EDIT */
scanf("%99[^\n]", input_text);
/*Can't use fgets*/
/*fgets(input_text, 100, input);*/
printf("Text: %s", input_text);
i++;
}
}
哪种方式有效,它读取所有输入行,但它将它们作为一个大行读取,忽略换行符和缩进字符、空格、制表符等。请阅读scanf手册页。删除格式字符串中的。检查返回值,我们将读取换行符前的一行,然后读取换行符。如果结果为零,则流中有一个换行符,If将尝试读取该换行符
char input_text[100];
char newlines[100];
int result = 0;
do {
result = scanf("%99[^\n]%99[\n]", input_text, newlines);//scan line to newline then trailing newline
if ( result == 0) {
result = scanf("%99[\n]", newlines);//scan leading newline
}
if ( result == 1) {
printf("Text: %s\n", input_text);//no newline so print line with newline
}
if ( result == 2) {
printf("Text: %s%s", input_text, newlines);//print line and newlines
}
} while ( result != EOF);
如果是我,知道我今天知道的,我会故意不及格。什么都没有,什么都没有通过尝试使用scanf读取输入行,可以获得正值。这完全是徒劳的。完成本练习后,您最多只能学到一些您永远不需要知道的东西,最坏的情况是,您可能会被诱导使用新发现的知识编写生产程序,尝试使用scanf读取输入,这对你和那些程序都没有任何好处。认真地说:告诉你的导师这是一个糟糕的作业。我知道你可以用以下一行来阅读:scanf%[^\n]s,text;->当线条很短或很长时,效果不好。@我同意这两种意见,但我遇到了scanf与fgets的1个角使用。如果扫描%99[^\n]%n,则输入文本,&n==1{…允许代码检测是否读取空字符,因为n是真实长度。当然,fgetc或getline是其他选项。在C中,文本行包括“\n”。每行由零个或多个字符加上一个终止新行字符组成。C11 7.21.2 2 2.在post中指定if input_text[100];函数结束时应包含“\n”。
char input_text[100];
char newlines[100];
int result = 0;
do {
result = scanf("%99[^\n]%99[\n]", input_text, newlines);//scan line to newline then trailing newline
if ( result == 0) {
result = scanf("%99[\n]", newlines);//scan leading newline
}
if ( result == 1) {
printf("Text: %s\n", input_text);//no newline so print line with newline
}
if ( result == 2) {
printf("Text: %s%s", input_text, newlines);//print line and newlines
}
} while ( result != EOF);