-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は私にそのコードを提供できますか?
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
データ型がテキストまたは文字列を簡単に取り扱います:ここで
コードがより一貫してフォーマットされインデントされていれば、ロジックに従う方が簡単かもしれません。 – Galik
[std :: string](http://en.cppreference.com/w/cpp/string/basic_string)と[std :: vector](http://en.cppreference)を使用すると、 .com/w/cpp/container/vector)を使用してください。 – Galik
作業コードを改善する場合は、[SE Code Review](https://codereview.stackexchange.com/)にお問い合わせください。 – user0042