저는 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 루프가 어디에서 끝나는 지 처음에는 명확하지 않습니다. –
'FILE * doesthiswork doesthiswork = fopen ("testWords.in", "r")은 무엇인가? 나는 이것이 당신의 진짜 코드라고 생각하지 않습니다. –
사실은 제 실제 코드입니다. 파일 이름이 필요하고 작동하는지 확신 할 수 없기 때문에 출력 파일의 이름을 지정했습니다. – user3579225