我的意图是阅读每一行的前5个单词。但是当我运行这个代码时,文本文件中的每个单词都会打印出来。有人能告诉我为什么会这样吗?
int main(空){
char const* const fileName = "text.dat";
FILE* file = fopen(fileName, "r");
if (!file) {
printf("\n Unable to open : %s ", fileName);
return -1;
}
char line[50];
while (fgets(line, 5, file)) {
printf("%s", line);
}
fclose(file);
return 0;}
我的意图是阅读每一行的前5个单词。但是当我运行这个代码时,文本文件中的每个单词都会打印出来。有人能告诉我为什么会这样吗?
发布于 2022-11-06 16:07:52
您可能希望使用字符串函数"strtok“来拆分和计数单词。使用您的初始代码,我添加了以下调整。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char const* const fileName = "text.dat";
FILE* file = fopen(fileName, "r");
if (!file)
{
printf("\n Unable to open : %s ", fileName);
return -1;
}
char line[129];
const char delim[2] = " ";
char * wd;
while (fgets(line, 128, file))
{
wd = strtok(line, delim);
int i = 0;
while (i < 5 && wd != NULL)
{
printf("%s ", wd);
wd = strtok(NULL, delim);
i++;
}
printf("\n");
}
fclose(file);
return 0;
}然后使用以下数据设置一个简单的文本文件。
Now is the time for all good men to come to the aid of their country.
The quick brown fox jumps over the lazy dog.以下是结果的输出。
@Dev:~/C_Programs/Console/Parse/bin/Release$ ./Parse
Now is the time for
The quick brown fox jumps 有关使用"strtok“函数的更多信息,您可能需要参考此链接strtok用法。
试一试,看看它是否符合你的项目精神。
https://stackoverflow.com/questions/74336477
复制相似问题