我有一个任务要编写一个代码,它应该在其中读取一个文本文件,然后编写一个输出文件,显示代码中每个参数的频率,即“整数 = 2,关键字 = 13,标识符 = 3 ...”
我写了一个代码,但我面临的问题是它总是将所有频率输出为 0。好像“整数++”和其他增量都不起作用。
你能告诉我我在这里做错了什么吗?
#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;
}