2017-10-08 66 views
-3

這是檢查給定字符串的代碼是identifierkeyword。下面是代碼:給定字符串是C++中的有效標識符或關鍵字

#include<stdio.h> 
#include<conio.h> 
#include<string.h> 
#include<ctype.h> 


int main(){ 

    int i = 0, flag = 0; 
    char a[10][10] = {"int", "float", "break", "long", "char", "for", "if", "switch", "else", "while"}, string[10]; 

    //clrscr(); 

    printf("Enter a string :"); 
    gets(string); 

    /*----Checking whether the string is in array a[][]----*/ 

    for(i = 0 ; i < 10; i++){ 
     if((strcmp(a[i], string) == 0)) 
      flag = 1; 
    } 

    /*----If it is in the array then it is a keyword----*/ 

    if(flag == 1) 
     printf("\n%s is a keyword ", string); 

    /*----Otherwise check whether the string is an identifier----*/ 
    else{ 
     flag = 0; 
     /*----Checking the 1st character*----*/ 

     if((string[0] == '_') || (isalpha(string[0]) != 0)){ 
      /*---Checking rest of the characters*---*/ 
      for(i = 1; string[i] != '\0'; i++) 
      if((isalnum(string[i]) == 0) && (string[i]!='_')) 
       flag = 1; 
     } 
     else 
      flag = 1; 
     if(flag == 0) 
      printf("\n%s is an identifier ", string); 
     else 
      printf("\n%s is neither a keyword nor an identifier ", string); 
    } 
     getch(); 
} 
  • 我想更輕鬆地做到這一點的代碼。是否有可能得到或確定所有關鍵字 而不在char中聲明?以及如何做到這一點?

S.O能否提供該代碼?

+1

如果您的代碼被更一致地格式化和縮進,則可能更容易遵循邏輯。 – Galik

+1

如果你使用[std :: string](http://en.cppreference.com/w/cpp/string/basic_string)和[std :: vector](http://en.cppreference),它會容易得多.com/w/cpp/container/vector)而不是數組和字符數組。 – Galik

+0

如果您有工作代碼需要改進,最好在[SE代碼審查](https://codereview.stackexchange.com/)上提問。 – user0042

回答

1

下面是一個簡單的方法:

static const std::string keywords[] = 
{ 
    "char", "class", 
    "struct", 
    /* ... */ 
}; 
static const size_t keyword_quantity = 
    sizeof(keywords)/sizeof(keywords[0]); 

std::string search_word; 
cin >> search_word; 

std::string const * const iterator = 
    std::find(&keywords[0], &keywords[keyword_quantity], 
       search_word); 
if (iterator != &keywords[keyword_quantity]) 
{ 
    cout << "Word is a keyword!\n"; 
} 

std::string數據類型使得文本或字符串處理更容易。
std::find函數很容易,所以你不必寫它(它已經過測試)。

相關問題