我有一个编写代码的任务,它应该读取一个文本文件,然后编写一个输出文件,显示代码中每个参数的频率,即“整数= 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;
}
答案 0 :(得分:2)
乍一看你的代码,我甚至很惊讶它甚至编译。即使这样, 形式的界限:
if(token=="+"||"-"||"*"||"/")
不要按照你的想法去做,你应该将if语句重写为
if (*token == '+' || *token == '-' || ... || *token == '/')
token是一个指针,所以你需要比较它的 value ,并使用条件语句的正确语法。
答案 1 :(得分:0)
您没有读取文件,您没有进行标记,并且您正在将指针与字符串文字进行比较,这是完全错误的。在C和标准库上阅读一下。