加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 带分隔符的Strtok行为

发布时间:2020-12-16 09:57:42 所属栏目:百科 来源:网络整理
导读:以下是代码段. #define TABLE_DELIMITER "::"int parse_n_store ( char *line ){ int i = 0; char *p = NULL; CPTR sensor_number = NULL,event_catagory = NULL,sensor_type = NULL,event_state= NULL,assertion = NULL,message_number = NULL,short_text =
以下是代码段.

#define TABLE_DELIMITER "::"
int parse_n_store ( char *line )
{

        int i = 0;
        char *p = NULL;
        CPTR sensor_number = NULL,event_catagory = NULL,sensor_type = NULL,event_state= NULL,assertion = NULL,message_number = NULL,short_text = NULL;

        for (p = strtok(line,TABLE_DELIMITER); p != NULL; p = strtok(NULL,TABLE_DELIMITER),i++ )
        {
                if ( i == 0 )
                        sensor_number=p;
                else if ( i == 1 )
                        sensor_type = p;
                else if ( i == 2 )
                        event_catagory = p;
                else if ( i == 3 )
                        event_state = p;
                else if ( i == 4 )
                        assertion = p;
                else if ( i == 5 )
                        message_number = p;
                else if ( i == 6 )
                        short_text = p;
        }

        printf ("%s %s %s %s %s %s %sn",sensor_number,event_catagory,sensor_type,event_state,assertion,message_number,short_text);
}

这很好用.但是,当“行”参数为“前面板内存状态:检测到可纠正的ECC /其他可纠正的内存错误;传感器(70,内存)”时

输出将是

70 SENSOR_SPECIFIC MEMORY STATE_00 True 8543前面板内存状态

其中short_text变量仅包含“前面板内存状态”而不是“前面板内存状态:检测到可纠正的ECC /其他可纠正的内存错误;传感器(70,内存)”

为什么strtok考虑将单个冒号作为分隔符?谁能解决这个问题.

解决方法

Why strtok considering a single colon as delimiter?

因为它在标准(C11)中指定:

7.24.5.8 The strtok function

[…]

  1. A sequence of calls to the strtok function breaks the string pointed to by s1 into a sequence of tokens,each of which is delimited by a character from the string pointed to by s2. The first call in the sequence has a non-null first argument; subsequent calls in the sequence have a null first argument. The separator string pointed to by s2 may be different from call to call.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读