时间限制 | 空间限制 |
---|---|
1000 ms |
65536 KB |
# 题目描述
shtog 定义了一种新的很简单的编程语言,但是这种语言不能直接被电脑执行,所以他希望可以用 c 语言编写一个简单的编译器对其进行编译,进而成功执行程序。
语言的语法很简单,其只包含两类语句:赋值语句、输出语句,每条语句占一行。
赋值语句的语法为:<变量名> < 值 >,其中 < 值 > 只可能是一个在 int
范围内的常数或一个在上面的代码中已经被赋值过的变量,同一个变量可以被重复多次赋值,新赋的值会覆盖之前被赋的值(和 C 语言逻辑一致),变量名由不超过 个大写或者小写字母组成且不会叫做 print
。
输出语句的语法为: print
<变量名>。注意,如果欲输出的变量名在之前的代码中未被赋过值(尚未定义),那么输出 line <行号>: print invalid name "<变量名>"!
(行号从 算起),否则则输出变量的值。
请你编写 C
语言程序帮 shtog 翻译并执行该语言编写的程序。
# 输入格式
一共不会超过 行。
一共若干行,每行一条语句,保证一定会出现有 print
语句。
# 输出格式
输出若干行,表示代码的执行结果(每条 print
语句对应一行输出)。
# 输入样例
a 3 | |
B a | |
print B | |
print b |
# 输出样例
3 | |
line 4: print invalid name "b"! |
# 题解:模拟
还是依题意模拟,不过这个模拟稍微复杂一些。几个模拟上的关键细节:
-
考虑用二维字符数组,存下已经出现过的所有变量名
-
我们可以不用
int
存下变量值,既然变量值不涉及运算,可以直接用字符数组存下。
参考代码:
#include <stdio.h> | |
#include <string.h> | |
#include <ctype.h> | |
int cnt, line; | |
char a[10], b[15], list[5010][10], val[5010][15]; | |
int main() | |
{ | |
// freopen("H.in", "r", stdin); | |
// freopen("H.out", "w", stdout); | |
while (~scanf("%s %s\n", a, b)) | |
{ | |
++ line; | |
if (strcmp(a, "print")) | |
{ | |
int ind = 1; | |
while (ind <= cnt && strcmp(a, list[ind])) | |
++ ind; | |
if (ind > cnt) | |
{ | |
cnt = ind; | |
strcat(list[ind], a); | |
} | |
if (!isupper(b[0]) && !islower(b[0])) | |
memcpy(val[ind], b, sizeof(b)); | |
else | |
{ | |
int pos = 1; | |
while (pos <= cnt && strcmp(b, list[pos])) | |
++ pos; | |
memcpy(val[ind], val[pos], sizeof(val[pos])); | |
} | |
} | |
else | |
{ | |
int pos = 1; | |
while (pos <= cnt && strcmp(b, list[pos])) | |
++ pos; | |
if (pos > cnt) | |
printf("line %d: print invalid name \"%s\"!\n", line, b); | |
else | |
printf("%s\n", val[pos]); | |
} | |
} | |
return 0; | |
} |