我正在学习 C 和它在文本文件中读取的任务之一,并让它输出格式化的文本文件。最终产品应如下所示:
1)"I must not fear.[4,17]
2)Fear is the mind-killer.[4,24]
3)Fear is the little-death that brings total obliteration.[8,56]
4)I will face my fear.[5,20]
.
.
.
13)oneWord_allAlone[1,16]
13 lines, 94 words, 481 characters
Line 10 has the most words (16)
Line 7 has the most characters (68)
我已经编写了代码并且可以得到一些接近的东西,但是信息是乱序的并且变量是错误的并且它切断了每个句子的第一个字母。我得到:
I must not fear0.)
[4, 16]
ear is the mind-killer.0)
[7 39]
ear is the little-death that brings total obliteration.0)
[14 92]
.
.
.
neWord_allAlone1)
[86 470]
1 lines, 20360 words, 110685 characters
line 1 has the most words with (86)
line 1 has the most characters with 470)
它从哪里获得 110685 个字符超出了我的范围。那么,话虽如此,我做错了什么?据我所知,我已经正确设置了所有变量,但输出顺序错误,第一个字符被截断,并且计数被 wayyyy 关闭。任何帮助深表感谢!这是我的代码:
#include <stdio.h>
#define IN 1
#define OUT 0
void main() {
int c = 0;
int numChars = 0;
int numWords = 0;
int numLines = 0;
int state = OUT;
int test = 0;
int largestNumChars = 0;
int largestNumWords = 0;
int totalNumChars = 0;
int totalNumWords = 0;
int lineWithMostChars = 0;
int lineWithMostWords = 0;
FILE *doesthiswork = fopen("testWords.in", "r");
while ((test = fgetc(doesthiswork)) != EOF) {
if ( test == '\n') {
++numLines;
}
while ((test = fgetc(doesthiswork)) != '\n') {
++numChars;
putchar(test);
if (test == ' ' || test == '\t' || test == '\n') {
state = OUT;
} else if (state == OUT){
state = IN;
++numWords;
}
totalNumWords = totalNumWords + numWords;
totalNumChars = totalNumChars + numChars;
}
if (largestNumChars == 0) {
largestNumChars = numChars;
} else if (largestNumChars < numChars) {
largestNumChars = numChars;
lineWithMostChars = numLines;
} else {
largestNumChars = largestNumChars;
lineWithMostChars = lineWithMostChars;
}
if (largestNumWords == 0) {
largestNumWords = numWords;
lineWithMostWords = numLines;
} else if (largestNumWords < numWords) {
largestNumWords = numWords;
lineWithMostWords = lineWithMostWords;
} else {
largestNumWords = largestNumWords;
}
printf("%d) %c [%d %d]\n",numLines, test, numWords, numChars);
}
printf("%d lines, %d words, %d characters\n",
numLines, totalNumWords, totalNumChars);
printf("line %d has the most words with (%d)\n",
lineWithMostWords, largestNumWords);
printf("line %d has the most characters with (%d)\n",
lineWithMostChars, largestNumChars);
}
最佳答案
好吧,首字母的去向是您通过第一个 fgetc
调用读取它们,但您不像使用第二次 fgetc
调用。
totalNumChars
如此之大,因为您定期向其中添加 numChars
,但您永远不会将 numChars
重置为零。
希望对您有所帮助。享受寻找和消除这些错误的乐趣吧!
关于c - 在 ansi c 中读取和格式化文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25597737/