首页 > 解决方案 > 如何在 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);
}

标签: cstructenumsunion

解决方案


如何在 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");
}

推荐阅读