#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'?究竟是什麼問題? –