2011-11-15 54 views
0
#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];

+0

elabolate你的問題。相反你可以使用if(temp_string.compare(reserved [i])== 0) –

+0

'temp_string'聲明在哪裏?我沒有看到它的聲明。 –

+4

你忽略顯示'temp_string'的定義,大概它也是'string'?究竟是什麼問題? –

回答

0

temp_string沒有聲明。

你把temp_string聲明爲字符串嗎? 對我來說,它打印保留關鍵字。

0

循環的結尾有點粗略;你失蹤了}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"); 

Here是破碎少的版本。