gpt4 book ai didi

c - 根据规则对从文件中读取的文本进行标记

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

我有一个编写代码的作业,其中应该读取一个文本文件,然后编写一个输出文件,显示代码中每个参数的频率,即“整数= 2,关键字= 13,标识符= 3。 ..”

我写了一个代码,但我面临的问题是它总是将所有频率输出为 0。好像“integer++”和其他增量不起作用。

你能告诉我我在这里做错了什么吗?

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

int main(void)
{

FILE *input; //file to read from
FILE *output; //file to write to
char *token=NULL;
int keywords=0, identifier=0, integer=0, real=0, relationOperator=0, ArtOperator=0, lPar=0, rPar=0, semicolon=0, assign=0, comma=0, etc=0;


input = fopen("input.txt", "r"); //read from file
if (input==NULL) {
printf("I couldn't open input.txt for reading.\n");
exit(0);
}

token=strstr(input, " "); //tokenize

while (token!=NULL) //start of loop
{
if(token=="%s"){
if(token=="main"||"a"||"b"){ //if identifier
identifier++;
}
else{ //if keyword
keywords++;
}
}
else if(token=="%d"){ //if integer
integer++;
}
else if(token=="%f"){ //if real number
real++;
}
else if(token==">"||"<"){ //if relation operator
relationOperator++;
}
else if(token=="+"||"-"||"*"||"/"){ //if arithmetic operator
ArtOperator++;
}
else if(token=="("){ //if left parenthesis
lPar++;
}
else if(token==")"){ //if right parenthesis
rPar++;
}
else if(token==";"){ //if semicolon
semicolon++;
}
else if(token=="="){ //if assignment operator
assign++;
}
else if(token==","){ //if comma
comma++;
}
else
{ //consider anything else as etc
etc++;
}
token=strtok(NULL, " ");
}//end of loop

output = fopen("output.txt", "w"); //write to file

if (output == NULL) {
printf("I couldn't open output.txt for writing.\n");
exit(0);
}

fprintf(output, "keywords = %d\n" ,keywords);
fprintf(output, "identifiers = %d\n" ,identifier);
fprintf(output, "integers = %d\n" ,integer);
fprintf(output, "real numbers = %d\n" ,real);
fprintf(output, "relation operators = %d\n" ,relationOperator);
fprintf(output, "arithmetic operator = %d\n" ,ArtOperator);
fprintf(output, "left parenthesis = %d\n" ,lPar);
fprintf(output, "right parenthesis = %d\n" ,rPar);
fprintf(output, "semicolons = %d\n" ,semicolon);
fprintf(output, "assignment operators = %d\n" ,assign);
fprintf(output, "commas = %d\n" ,comma);
fprintf(output, "other characters = %d\n" ,etc);

fclose(output); //close output file

return 0;
}

最佳答案

乍一看你的代码,我很惊讶它竟然能编译。即使确实如此,表格线:

if(token=="+"||"-"||"*"||"/")

不要做你认为他们做的事情,你应该将 if 语句重写为

if (*token == '+' || *token == '-' || ... || *token == '/')

token 是一个指针,因此您需要比较它的,当然,并对条件语句使用正确的语法。

关于c - 根据规则对从文件中读取的文本进行标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15791012/

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