-3
这是检查给定字符串的代码是identifier
或keyword
。下面是代码:给定字符串是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能否提供该代码?
如果您的代码被更一致地格式化和缩进,则可能更容易遵循逻辑。 – Galik
如果你使用[std :: string](http://en.cppreference.com/w/cpp/string/basic_string)和[std :: vector](http://en.cppreference),它会容易得多.com/w/cpp/container/vector)而不是数组和字符数组。 – Galik
如果您有工作代码需要改进,最好在[SE代码审查](https://codereview.stackexchange.com/)上提问。 – user0042