我必须获取文件中字符串的第一个单词,并将其与一些单词进行比较,如果它们与我比较的单词相同,则递增计数器,然后在末尾显示每个单词的数量. 我总是得到正确数量的前两个单词,其他单词都是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 ,不知道为什么.

推荐答案

try 使用以下代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_WORD_LENGTH 100

int main() {
    FILE *file;
    char filename[] = "your_file.txt"; // Replace with your file name
    char line[MAX_WORD_LENGTH];
    char word[MAX_WORD_LENGTH];

    // Define the words to compare
    char targetWords[][MAX_WORD_LENGTH] = {"apple", "banana", "orange"};
    int wordCount[sizeof(targetWords) / MAX_WORD_LENGTH] = {0};

    file = fopen(filename, "r");
    if (file == NULL) {
        perror("Error opening file");
        return 1;
    }

    while (fgets(line, sizeof(line), file) != NULL) {
        // Extract the first word from the line
        sscanf(line, "%s", word);

        // Compare the word with the target words
        for (int i = 0; i < sizeof(targetWords) / MAX_WORD_LENGTH; ++i) {
            if (strcmp(word, targetWords[i]) == 0) {
                wordCount[i]++;
                break; // No need to check further if a match is found
            }
        }
    }

    fclose(file);

    // Display the results
    for (int i = 0; i < sizeof(targetWords) / MAX_WORD_LENGTH; ++i) {
        printf("%s: %d\n", targetWords[i], wordCount[i]);
    }

    return 0;
}

C++相关问答推荐

使用sd-设备列举设备导致seg错误

理解C中的指针定义

如何将FileFilter添加到FileDialog GTK 4

球体—立方体重叠:无、部分或全部?

为什么写入系统调用打印的字符数不正确?

va_copy的使用是未定义的行为吗?

如何设置指针指向在函数中初始化的复合文字中的整数?

如何知道我是否从非阻塞套接字读取所有内容

可以将C变量限制为特定的读/写速度吗?

在列表中插入Int指针(C)

C在声明带有值的数组时,声明大小有用吗?

将uintptr_t添加到指针是否对称?

FRIDA-服务器成为端口扫描的目标?

使用TCL C API导航到列表中的元素

为什么用非常数指针变量改变常量静态变量时会出现分段错误?

在下面的C程序中,.Ap0是如何解释的?

在printf()中用%.*S格式填充长度为0的字符串是否会调用任何UB?如果是,是哪一个?

我可以使用Windows SDK';s IN6_IS_ADDR_LOOPBACK等,尽管没有文档?

当循环变量在溢出时未定义时,可以进行哪些优化?

如何在C中以0x格式打印十六进制值