このプログラムでは、 ( ) ; = といった4種類のトークンも判別することが可能なのですが、実行してもこれらのトークンを判別してくれません。なぜ実行されないのでしょうか。教えてください。
ちなみに、普通の文字列ではきちんと実行できます。
#include <stdio.h>
#include <ctype.h>
/* 識別子を構成する一文字目か? */
int isIdentFirstChar(int c)
{
return isalpha(c) || c == '_';
}
/* 識別子を構成する文字か? */
int isIdentChar(int c)
{
return isalpha(c) || isdigit(c) || c == '_';
}
/* 数値を構成する一文字目か? */
int isIntFirstChar(int c)
{
return isdigit(c);
}
/* 数値を構成する文字か? */
int isIntChar(int c)
{
return isdigit(c) || c == '_';
}
/*
識別子に属さない最初の文字へのポインタを返す
※ 一文字目は識別子の文字であることは仮定している
*/
char *getIdent(char *input)
{
while (isIdentChar(*++input)) /* empty */;
return input;
}
/*
数値文字列に属さない最初の文字へのポインタを返す
※ 一文字目は数値を構成する文字であることは仮定している
*/
char *getInt(char *input, int *pv)
{
int c;
*pv = isdigit(c = *input) ? c - '0' : 0;
while (isIntChar(c = *++input)) if (isdigit(c)) *pv = 10 * *pv + c - '0';
return input;
}
/* 空白類をスキップ(ただし、改行で止まる) */
char *skipSpaces(char *s)
{
while (isspace(*s) && *s != '\n') ++s;
return s;
}
int lex(char *input)
{
int num_of_tokens = 0;
while (*(input = skipSpaces(input))) {
char *endp;
int c, v;
if (isIdentFirstChar(*input)) {
c = *(endp = getIdent(input));
*endp = '\0';
printf("識別子: %s (%d文字)\n", input, (int)(endp - input));
*(input = endp) = c;
} else if (isIntFirstChar(*input)) {
endp = getInt(input, &v);
printf("整数定数: %d (%d文字)\n", v, (int)(endp - input));
input = endp;
} else {
switch (c = *input++) {
case '+': case '-': case '*': case '/':
printf ("演算子:%c\n", c);
break;
case '(': case ')': case ';': case '=':
printf ("区切子:%c\n", c);
break;
default:
if (c == '\n') printf("改行\n");
else printf("エラー:%cは不正な文字\n", c);
continue;
}
}
++num_of_tokens;
}
return num_of_tokens;
}
int main(int argc, char* argv[/url])
{
if (argc != 2) {
fprintf(stderr, "使いかた: %s '一行のテキスト'\n", argv[0]);
return 1;
}
printf("トークン数は%d個!\n", lex(argv[1]));
return 0;
}
(実行結果)$./conp abc
$識別子:abc(3文字)
$トークン数は1個
$./conp abc(12)
$bash: syntax error near unexpected token'('
$