gpt4 book ai didi

数一下总数文件中的关键字

转载 作者:行者123 更新时间:2023-11-30 18:44:37 26 4
gpt4 key购买 nike

我想统计总数。文件中的关键字,但代码对用于声明变量的关键字进行计数。

void main()
{
//2d array used to store the keywords but few of them are used.

char key[32][12]={"int","char","while","for","if","else"};

//cnt is used to count the occurrence of the keyword in the file.

int cnt=0,i;

//used to store the string that is read line by line.

char ch[100];

FILE *fp=fopen("key.c","r");

//to check whether file exists or not

if(fp=='\0')
{
printf("file not found..\n");
exit(0);
}
//to extract the word till it don't reach the end of file

while((fscanf(fp,"%s",ch))!=EOF)
{
//compare the keyword with the word present in the file.

for(i=0;i<32;i++)
{
// compare the keyword with the string in ch.

if(strcmp(key[i],ch)==0) {

//just to check which keyword is printed.
printf("\nkeyword is : %s",ch);
cnt++;
}
}
}
printf("\n Total no. of keywords are : %d", cnt);
fclose(fp);
}

预期输出应该是:

   Total no. of keywords are : 7

实际输出即将到来:

   Total no. of keywords are : 3

最佳答案

fscanf(fp,"%s",ch) 将匹配一系列非空白字符(请参阅 cpp reference ),因此在您的情况下 forwhileif 不会作为单个单词进行匹配 - 因为它们后面没有空格。

关于数一下总数文件中的关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57533703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com