gpt4 book ai didi

c - 使用 fgets 获取同一行上的两行

转载 作者:行者123 更新时间:2023-11-30 16:11:39 24 4
gpt4 key购买 nike

我正在尝试在同一行上打印文件中的每两行。

文件看起来像:

Supposedly there are over one
million words in the English Language
We trimmed some fat to take
away really odd words and determiners

我想要得到:

Supposedly there are over one, million words in the English Language
We trimmed some fat to take, away really odd words and determiners

到目前为止,我使用了 fgets() 函数来显示 .txt 文件中的数据,但我不知道如何将 .txt 文件的每两行放在同一行上。我得到相同的输出。

char line[110]; // max numbers of characters in line
while (fgets(line, 109, stdin)) {
printf("%s", line);
}
return 0;

我希望输出像我之前提到的那样:

Supposedly there are over one, million words in the English Language
We trimmed some fat to take, away really odd words and determiners

最佳答案

您需要从缓冲区中删除奇数行号的尾随 \n 然后打印它。

  int lineNumber = 1;
char line[110]; // max numbers of characters in line

while(fgets(line, sizeof line, stdin))
{
if (lineNumber&1) {

char *pos;
if ((pos=strchr(line, '\n')) != NULL) {
*pos = '\0';
printf("%s ",line);
}
}
else {
printf (" %s", line);
}
lineNumber++;
}

关于c - 使用 fgets 获取同一行上的两行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58557041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com