2011-11-15 2 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++의 문자열을 비교할 수 없습니다.

EDIT : temp_token은 임시 저장 단어입니다. 이 단어는이 줄에 문자를 추가하여 작성되었습니다. temp_string += temp_token[i];

+0

당신의 문제를 구체화하십시오. 대신에 if (temp_string.compare (reserved [i]) == 0) –

+0

어디에서'temp_string'을 선언 했습니까? 나는 그것이 선언이라고 생각하지 않는다. –

+4

'temp_string'의 정의를 보여주지 않으려합니다. 아마도'string'일까요? 문제가 정확히 무엇입니까? –

답변

0

temp_string이 선언되지 않았습니다.

temp_string을 (를) 문자열로 선언 했습니까? 나를 위해 키워드를 위해 예약 됨을 인쇄합니다.

0

루프의 끝 부분은 약간 스케치됩니다. 당신은 실종 된 }을 가지고 있고, ungetc()은 완전히 잘못된 것처럼 들립니다. 당신은 (당신이 정말로 그것을 어떤 이유로 세계 수 있도록하려면 그 시점에서 clear() 전화, 또는) 또한 그냥 웁니다 루프 전에 temp_string를 선언

 } 
     cha = fgetc(pfile); 
    } 
    fclose(pfile); 
} 

  cha = ungetc(cha, pfile); 
      count = 0; 
     } 
     fclose(pfile); 
} 

을 변경해야 . , 더 나은 여전히 ​​

std::string temp_string(temp_token, temp_token+count); 

또는 임시 버퍼 없애, 당신은 문자를 읽을 때 문자열을 구축 : 더 나은 여전히 ​​무의미한 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 덜 깨진 버전입니다.

관련 문제