2011-11-15 55 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是破碎少的版本。