2017-10-08 10 views
-3

Ceci est un code de vérification d'une chaîne donnée est un identifier ou un keyword. Voici le code:une chaîne donnée est un identifiant ou un mot-clé valide en 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(); 
} 
  • Je veux faire ce code plus facilement. Et est-il possible d'obtenir ou d'identifier les tous les mots-clés sans déclarer dans le char? Et comment faire ça?

Est-ce que S.O peut me fournir ce code?

+1

Si votre code était formaté de façon plus cohérente et indenté, il pourrait être plus facile de suivre la logique. – Galik

+1

Ce serait beaucoup plus facile si vous utilisiez [std :: string] (http://en.cppreference.com/w/cpp/string/basic_string) et [std :: vector] (http: //en.cppreference .com/w/cpp/container/vector) plutôt que des tableaux et des tableaux de caractères. – Galik

+0

Si vous avez du code de travail à améliorer, mieux vaut demander à [SE Code Review] (https://codereview.stackexchange.com/). – user0042

Répondre

1

Voici une méthode simple:

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"; 
} 

Le type de données std::string rend la manipulation du texte ou une chaîne plus facile.
La fonction std::find est facile, vous n'avez donc pas à l'écrire (et c'est déjà testé).