[英]Cannot compare strings in C++
#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);
}
我對reserved [i]和temp_string字符串之間的比較語句有疑問。 我無法成功打印“保留”,它始終打印“ ALPHA”。 據您所知,這是一個從文件(hello.cel)獲取每個字符並打印每個標記的類型的程序。
編輯:temp_token是一個字符串,我是臨時存儲的單詞。 通過在此行添加字符來制作這些單詞temp_string += temp_token[i];
未聲明temp_string。
您是否已將temp_string聲明為字符串? 對我來說,它會打印“保留給關鍵字”。
循環的末尾有些粗略。 您缺少}
,而ungetc()
聽起來完全是錯誤的事情。 你需要改變
cha = ungetc(cha, pfile);
count = 0;
}
fclose(pfile);
}
至
}
cha = fgetc(pfile);
}
fclose(pfile);
}
還要在填充它的循環之前聲明temp_string
(或者,如果出於某種原因真的希望它是全局的,請在那一點調用clear()
)。 更好的是,在刪除無意義的count--
之后,從緩沖區對其進行初始化-:
std::string temp_string(temp_token, temp_token+count);
甚至更好的是,擺脫臨時緩沖區,並在讀取字符時構建字符串:
std::string token(1, cha);
cha = fgetc(pfile);
while(isdigit(cha) || isalpha(cha) || cha == '_')
{
if(token.size() < 30)
{
token.push_back(cha);
}
cha = fgetc(pfile);
}
最后,僅在檢查所有保留令牌后才打印ALPHA
:
bool is_reserved = false;
for(i = 0; i < 25; i++)
{
if(token == reserved[i])
{
is_reserved = true;
break;
}
}
printf(": %s\n", is_reserved ? "RESERVED" : "ALPHA");
這是一個不太壞的版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.