#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string>
#include <iostream>
FILE *pfile;
using namespace std;
string temp_string;
string reserved[25] = {"AND", "CALL", "DECLARE", "DO", "ELSE", "ENDDECLARE", "ENDFUNCTION", "ENDIF", "ENDPROCEDURE", "ENDPROGRAM", "EXIT", "FALSE", "FOR", "FUNCTION", "IF", "IN", "INOUT", "NOT","OR", "PROCEDURE", "PROGRAM", "RETURN", "THEN", "TRUE", "WHILE"};
int main(void)
{
pfile = fopen("hello.cel", "r");
char cha, temp_token[30], temp;
int count = 0, check = 1, i;
cha = fgetc(pfile);
while (cha != EOF)
{
if(isalpha(cha) || cha == '_')
{
temp_token[0] = cha;
count = 1;
cha = fgetc(pfile);
while(isdigit(cha) || isalpha(cha) || cha == '_')
{
if(count < 30)
{
temp_token[count] = cha;
count++;
}
cha = fgetc(pfile);
}
count--;
for(i = 0; i <= count; i++)
{
temp_string += temp_token[i];
}
cout << temp_string;
for(i = 0; i < 25; i++)
{
if(temp_string == reserved[i])
{
printf(": RESERVED\n");
}
else
{
printf(": ALPHA\n");
}
}
cha = ungetc(cha, pfile);
count = 0;
}
fclose(pfile);
}
我在保留的[i]和temp_string字符串之间的比较语句有问题。我无法成功打印“RESERVED”,它总是打印“ALPHA”。 据您所知,这是一个程序,它从文件(hello.cel)中获取每个字符并打印每个标记的类型。无法比较C++中的字符串
编辑:temp_token是一个字符串我临时存储的话。这个单词已经通过在这一行添加字符进行了temp_string += temp_token[i];
elabolate你的问题。相反你可以使用if(temp_string.compare(reserved [i])== 0) –
'temp_string'声明在哪里?我没有看到它的声明。 –
你忽略显示'temp_string'的定义,大概它也是'string'?究竟是什么问题? –