c - 如何在 C 中打印字符串或整数?
问题描述
我有sturct token_t
下面的。它里面有两件事。
- 类型(枚举)
- 价值(联合)
value 是 union 的原因,例如 token 可以是数字或字符串。主要问题是我无法设计一个合适的函数来为我打印这个令牌。看看我的void print_token(token_t* token)
功能。我知道这很可怕。只是因为printf()
只打印 %d (十进制)或 %s (字符串),我无法打印出我的令牌。无论值是什么,我都希望我的函数打印令牌。
// ===========================================================================
typedef enum token_type_t
{
ID, // Identifier
STR, // String
WHS, // Whitespace
LPR, // Left Parenthesis
RPR, // Right Parenthesis
LCB, // Left Curly Bracket
RCB, // Right Curly Bracket
LSB, // Left Square Bracket
RSB, // Left Square Bracket
EOF, // End Of File
EQL, // Equal Sign
SEM, // Semicolon
} token_type_t;
typedef union token_value_t
{
char* str_value;
int int_value;
} token_value_t;
typedef struct token_t
{
token_type_t type;
token_value_t value;
} token_t;
// ===========================================================================
// Here's the problem. I want this function to print the token no matter what type
// the value is, I want it to be dynamic. Is there any way to do that?
void print_token(token_t* token)
{
printf("Token { type: %d, value: %s }\n", token->type, token->value);
}
解决方案
如何在 C 中打印字符串或整数?
printf()
根据类型使用不同的。
void print_token(const token_t* token) {
printf("Token { type: %d, value: ", token->type);
switch (token->type) {
case ID: printf("%d", token->value.int_value); break;
case STR: printf("\"%s\"", token->value.str_value); break;
// TBD code for other cases
}
printf(" }\n");
}
推荐阅读
- r - eval 中的错误(predvars、data、env):找不到对象“V1”
- python-3.x - 如果匹配条件,如何使用 python 更改 .xlsx 单元格的颜色,如果不保留旧颜色
- angular - 在实时数据库中保存非常大的字符串 - 最佳实践?
- python - 如何从 URL 获取 python 函数返回值?
- python - 用字符串枚举列表会给出错误的结果
- sql - AWS Athena - 如何将字符串列转换为日期?(列包括空)
- jenkins - 本地主机上的 Jenkins 配置
- javascript - 如何通过搜索子元素字符串来选择父元素?
- json - 在 Oracle 中解析属性超过 4000 的 JSON
- javascript - UTF-8 到 Windows-1252