我对C编程相当陌生,所以我正在使用fgets()和sscanf()从文件中读取数据。我建立了一个真正简单的实验在这里:为什么printf只打印字符串中的第一个单词?
#include <stdio.h>
#include <stdlib.h>
main()
{
char szInputBuffer[100];
FILE *pFile;
char szInput[100];
int i;
pFile = fopen("MyFile.txt", "r");
printf("This is the input: \n\n");
for (i = 0; i <= 2; ++i)
{
fgets(szInputBuffer, 100, pFile);
sscanf(szInputBuffer, "%s", szInput);
printf("%s", szInput);
}
}
我从MyFile.txt的读取其中包含简单:
This is more input.
The next line of Input.
More input here.
我的输出如何过是:
This is the input:
ThisTheMore
是哪个来自每一行的第一个词。我发现,当我添加第二个%s的printf语句像这样:
printf("%s%s", szInput);
那我实现所需的输出:
This is the input:
This is more input.
The next line of Input.
More input here.
可有人请给我讲解一下?我从来没有听说过使用第二个占位符来获取整个字符串。我一直没有找到任何有助于解决我的问题。我已经在类中看到了只在打印语句中使用一个%s并且打印整个字符串的示例程序。感谢您帮助一位好奇的程序员!
P.S我使用Geany IDE运行Ubuntu 14.04 LTS。我知道你们中有些人会问这个问题。
'sscanf'的'%s'说明符表示读取第一个单词。如果你想打印整行,那么就跳过 – 2015-02-24 04:12:25
的步骤,给出比printf的后续参数更多的格式说明符,导致未定义的行为;你不能真正阅读任何事情后 – 2015-02-24 04:15:15
据我所知,你使用sscanf是不必要的。 fgets调用将从文件中检索文本。我会抛弃sscanf并打印出szInputBuffer。 – user3647894 2015-02-24 04:15:53