我正在學習C和它在文本文件中讀取的任務之一,並讓它輸出格式化的文本文件。最終的產品應該是這樣的:閱讀和格式化文本文件在ansi 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個字符超出了我。所以,就這樣說,我做錯了什麼?據我所知,我有所有的變量設置正確,但輸出的順序是錯誤的,第一個字符被切斷,並計數是有點兒關閉。任何幫助深表感謝!這裏是我的代碼:
#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);
}
如果您希望其他人能夠讀取您的代碼(而不是絕望地舉起雙手),請*一致並正確地對齊您的縮進。例如,乍一看你的第二個'while'循環結束時,一點都不清楚。 – 2014-09-01 01:17:32
什麼是'FILE * doesthiswork doesthiswork = fopen(「testWords.in」,「r」);'所有關於?我不認爲這是你的真實代碼。 – 2014-09-01 01:37:59
這實際上是我真正的代碼。我將輸出文件命名爲doesthiswork,因爲我不確定它是否會工作並需要文件名。 – user3579225 2014-09-01 01:39:39