【发布时间】:2015-05-26 05:59:50
【问题描述】:
我是编程新手,所以请善待。
目前我正在尝试编写一个程序,它打开一个文本文件,读取两个单词,在文本文件中搜索,计算这两个单词出现的次数,然后最后打印第一个单词出现的第一行.
到目前为止,这是我所做的:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
FILE *infile;
char inputWord1[100], inputWord2[100], filename[100], wordInText[100], line[500];
int i, count, strComp, word1Count, word2Count, wordLen, lineCount;
char c;
int main() {
printf("Enter the first word: ");
gets(inputWord1);
printf("Enter the second word: ");
gets(inputWord2);
printf("Enter the file name: ");
gets(filename);
infile = fopen(filename, "r");
if(infile == NULL) {
printf("Error");
exit(1);
}
word1Count = 0; word2Count = 0; lineCount = 1;
while(fscanf(infile, "%s", wordInText) != EOF) {
wordLen = strlen(wordInText);
for(i = 0; i < wordLen; i++) {
if(wordInText[i] >= 65 && wordInText[i] <= 90) {
wordInText[i] = wordInText[i] + 32;
}
}
for(c = getc(infile); c != EOF; c = getc(infile)) {
if(c == '\n') {
lineCount = lineCount + 1;
}
}
strComp = strcmp(wordInText, inputWord1);
if(strComp == 0) {
word1Count++;
if(word1Count == 1) {
for(int x = lineCount; x <= lineCount; x++) {
fgets(line, 500, infile);
printf("%s\n", line);
}
}
}
strComp = strcmp(wordInText, inputWord2);
if(strComp == 0) {
word2Count++;
}
}
printf("Word 1 appears %d times\n", word1Count);
printf("Word 2 appears %d times\n", word2Count);
}
所以这一切都有效,除了:
strComp = strcmp(wordInText, inputWord1);
if(strComp == 0) {
word1Count++;
if(word1Count == 1) {
for(int x = lineCount; x <= lineCount; x++) {
fgets(line, 500, infile);
printf("%s\n", line);
}
}
}
最后一个 for 循环不能正常工作。它打印出 \n 但不打印该行。我真的不知道为什么它不起作用。所有其他部分工作正常。
如果有人对如何解决此问题有任何想法,我将不胜感激。请记住,我只知道基本的 C 函数,我还没有完全完成这个程序(仍然需要将输入的单词转换为小写)。
【问题讨论】:
-
你确定要
for(int x = lineCount; x <= lineCount; x++)吗? -
您需要逐行扫描您的文件。复制第一行。然后显示字数,最后转储重复的行。
-
gets()不好,使用fgets()slways。 :-) -
@Ôrel 你能详细解释一下吗? SouravGhosh 我确实使用
fgets()来检索行,然后我使用gets来获取与文件无关的字符串。谢谢大家的帮助 -
忽略所有其他问题,当您循环计算行数时,您会消耗文件的所有字符。那么当你
fgets(line, 500, infile);你已经在文件的末尾了。