从C中的文本文件计算关键字

问题描述 投票:1回答:3
#include <stdio.h>  
#include <stdlib.h>
#include <string.h>


int c;

char* lib[5] = { "auto", "break", "char", "case", "const" };
char str[1000];
char buffer[300];
FILE *fp;

int main(){

    c = 0;

    fp = fopen("filename.txt", "r");

    if (fp == NULL){
        perror("Error in reading file");
    }

    if (fp != NULL){
        for (int j = 0; j < 5; j++){
            while (fgets(str, sizeof(buffer), fp) != NULL){
                if (strstr(str, lib[j]) != NULL) {
                    c++;
                }
            }
        }
        printf("%d", c);
    }
    while (1){};
}

所以我试图计算文本文件中关键字的数量。该代码将无法编译,并指出问题出在for循环和strstr争论周围。在以前的尝试中,它将编译,但不计算关键字的数量,它只打印0。任何想法都可以解决,以便代码可以编译,或者是一种用于计算文本文件中关键字数量的简单方法。 。

代码段将非常有帮助。

c visual-studio-2012
3个回答
1
投票

您的主要问题是(在您对其进行编辑之前)您已经正确地嵌套了输入循环,并且搜索循环反向了。


1
投票

要使代码运行,只需将while循环与for循环交换。


0
投票

我有类似的问题,但我想计算文件文本文件中变量的数量。假设我的txt文件中有此文件;b = 5;abc = b * 5;

© www.soinside.com 2019 - 2024. All rights reserved.