【问题标题】:a given string is valid identifier or keyword in c++ [closed]给定的字符串是c ++中的有效标识符或关键字[关闭]
【发布时间】:2017-10-08 16:45:54
【问题描述】:

这是检查给定字符串是identifier 还是keyword 的代码。代码如下:

#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();
}
  • 我想更轻松地编写此代码。是否有可能获得或识别 所有关键字都没有在字符中声明?以及如何做到这一点?

S.O 可以提供给我那个代码吗?

【问题讨论】:

  • 如果您的代码格式和缩进更一致,则可能更容易遵循逻辑。
  • 如果你使用std::stringstd::vector而不是数组和字符数组会容易很多。
  • 如果你有工作代码需要改进,最好在SE Code Review询问。
  • 如何使用 std::string 和 std::vector 轻松做到这一点?如果您提供代码@Galik,那就太好了
  • @RashedSami 这不是一个教程写作网站。你可以在谷歌上搜索教程,或者更好的是,从一本好书开始工作:stackoverflow.com/questions/388242/…

标签: c++ keyword identifier strcmp


【解决方案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 函数很简单,因此您不必编写它(并且它已经过测试)。

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 2020-12-21
    相关资源
    最近更新 更多