我必须获取文件中字符串的第一个单词,并将其与一些单词进行比较,如果它们与我比较的单词相同,则递增计数器,然后在末尾显示每个单词的数量. 我总是得到正确数量的前两个单词,其他单词都是0,或者全是0. 如果能帮上忙我会很感激的.
试着通过做以下事情来做:
#include <stdio.h>
#include <string.h>
int main() {
FILE *fpl = fopen("your_file.txt", "r");
if (fpl != NULL) {
printf("File opened\n");
char vetor[500];
char firstword[11];
int alamedas = 0;
while (fgets(vetor, 500, fpl)) {
for (int i = 0; i < 100; i++) {
if (vetor[i] == 'A' && vetor[i + 6] == 'a') {
int n = 0;
while (n < 7) {
firstword[n] = vetor[i];
i++;
n++;
}
firstword[n] = '\0';
if (strcmp("Alameda", firstword) == 0) {
alamedas += 1;
}
}
}
}
fclose(fpl);
printf("Alamedas - %d\n", alamedas);
} else {
printf("Can't open file\n");
}
return 0;
}
那么如果我再加上一个If,就像第一个If之后的第一个For一样,它不会加到自己的计数中go ,不知道为什么.