gpt4 book ai didi

从文本文件中一个一个地计算字符

转载 作者:行者123 更新时间:2023-12-02 01:32:09 25 4
gpt4 key购买 nike

我的程序需要从文本文件中获取输入并将其输出到单行。

但是,如果单个行上的字符数超过 60,则应该换行。

我目前的代码:

 int main(int argc, char *argv[]){
FILE *pFile;
char x[10];
char *token;
pFile = fopen("test5.txt","r");
int wordLength;
int totalCharLength;
char newline[10] = "newline";


if(pFile != NULL){
while (fgets(x, sizeof(x), pFile) != NULL) {
token = strtok(x,"\r\n");
if(token != NULL){
printf("%s",x);

}

else{
printf("%s",x);
}
//counter++;
wordLength = strlen(x);
totalCharLength += wordLength;
printf("%d",totalCharLength);
if(totalCharLength == 60){
printf("%s",newline);
}

}

fclose(pFile);
}
}

文本文件:

 a dog chased 

a cat up the

tree. The cat

looked at the dog from

the top of the tree.

有 5 条单独的线。哪个显示这个。这并非全部在一条线上。

输出:

 a dog chased a cat up the tree. The cat looked at the dog from the top of the tree.

现在程序需要能够获取该格式的输入文本并在一行中打印出来。

所以上面的输出应该在第二个单词“dog”之前的第 60 个字符处换行。

但是我想添加一个功能,以便有一个字符计数器,当字符数 = 60 时打印一个新行。

现在通过更多的调试我添加了代码

 printf("%d",totalCharLength);

就在 if(totalCharLength==60) 行之前,我意识到字符是按随机增量而不是一个一个地计算的。输出:

 a dog cha9sed 13a cat up 22the 26tree. The35 cat 40looked at49 the dog 58 from 63 the top o72f the tre81e.  85

所以这说明它不是逐字统计的。但是,当我将 charx[10] 更改为较低的值时,它不会在一行上打印所有内容。它会留下空隙。

示例:将 charx[10] 更改为 charx[2]

这正确地逐个字符地获取,但输出不在一行中。

只有当一行中的字符超过 60 时才应该换行。不是 14(第一行)。

 a2 3d4o5g6 7c8h9a10s11e12d13 14
30a17 18c19a20t21 22u23p24 25t26h27e28 29
46t32r33e34e35.36 37T38h39e40 41c42a43t44 45
71l48o49o50k51e52d53 54a55t56 57t58h59e60newline 61d62o63g64 65f66r67o68m69 70
72t73h74e75 76t77o78p79 80o81f82 83t84h85e86 87t88r89e90e91.92 93 94

最佳答案

我认为您最好单独打印每个字符,并在添加换行符之前检查空格。

类似于:

((charCount > 60) && (currentChar == ' ')) {
// print newline and reset counter
printf("\n");
charCount = 0;
}

编辑:在任何事情之前检查当前字符是否已经是换行符并跳过它。还要检查回车 \r,因为在 Windows 中换行符是 \r\n

#include <stdio.h>

int main(void) {
FILE *f = fopen("test.txt", "r");
if(!f) {
printf("File not found.\n");
return 1;
}

char c;
int cCount = 0;
while((c = fgetc(f)) != EOF) {
if(c == '\r') continue;
if(c == '\n') c = ' ';

printf("%c", c);
if((cCount++ > 60) && (c == ' ')) {
printf("\n");
cCount = 0;
}
}

fclose(f);
return 0;
}

关于从文本文件中一个一个地计算字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509070/

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