初始化结构,使用数组 [英] Initializing struct, using an array

查看:89
本文介绍了初始化结构,使用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个数组的:

const string a_strs[] = {"cr=1", "ag=2", "gnd=U", "prl=12", "av=123", "sz=345", "rc=6", "pc=12345"};
const string b_strs[] = {"cr=2", "sz=345", "ag=10", "gnd=M", "prl=11", "rc=6", "cp=34", "cv=54", "av=654", "ct=77", "pc=12345"};

然后我需要分析出'=',然后把这些值的结构。 (居委键映射到在结构中的关键FC),这是形式为:

which i then need to parse out for '=' and then put the values in the struct. (the rc key maps to the fc key in the struct), which is in the form of:

struct predict_cache_key {
    pck() :
        av_id(0),
        sz_id(0),
        cr_id(0),
        cp_id(0),
        cv_id(0),
        ct_id(0),
        fc(0),
        gnd(0),
        ag(0),
        pc(0),
        prl_id(0)
    { }

    int av_id;
    int sz_id;
    int cr_id;
    int cp_id; 
    int cv_id;
    int ct_id;
    int fc;
    char gnd;
    int ag;
    int pc;
    long prl_id;
};

我遇到的问题是,阵列的不在序列或相同序列的结构域。所以,我需要检查每一个,然后拿出一个方案,把同样进入结构。

The problem I am encountering is that the array's are not in sequence or in the same sequence as the struct fields. So, I need to check each and then come up with a scheme to put the same into the struct.

在使用C或C ++来解决上述任何帮助吗?

Any help in using C or C++ to solve the above?

推荐答案

这应该不会太难。你的第一个问题是,你没有一个固定大小的数组,所以你必须通过数组的大小,还是什么我倒是preFER您做出阵列NULL结尾的,例如

This shouldn't be too hard. Your first problem is that you don't have a fixed sized array, so you'd have to pass the size of the array, or what I'd prefer you make the arrays NULL-terminated, e.g.

常量字符串a_strs [] = {CR = 1,AG = 2,GND = U,NULL};

然后我会写一个解析字符串(私人)辅助功能:

Then I would write a (private) helper function that parse the string:


bool
parse_string(const string &str, char *buffer, size_t b_size, int *num)
{
    char *ptr;

    strncpy(buffer, str.c_str(), b_size);
    buffer[b_size - 1] = 0;

    /* find the '=' */
    ptr = strchr(buffer, '=');

    if (!ptr) return false;

    *ptr = '\0';
    ptr++;

    *num = atoi(ptr);

    return true;
}

那么你可以做什么qrdl曾建议。

then you can do what qrdl has suggested.

在for循环的简单:


for (const string *cur_str = array; *cur_str; cur_str++)
{
   char key[128];
   int value = 0;

   if (!parse_string(*cur_string, key, sizeof(key), &value)
       continue;

   /* and here what qrdl suggested */
   if (!strcmp(key, "cr")) cr_id = value;
   else if ...
}

编辑:你应该使用的,而不是长期int和蒂,而不是与atoi,因为你的prl_id长的类型。第二,如果有可能的'='后错格式化数字,你应该使用与strtol,它可以捕获错误。

you should probably use long instead of int and atol instead of atoi, because your prl_id is of the type long. Second if there could be wrong formated numbers after the '=', you should use strtol, which can catch errors.

这篇关于初始化结构,使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆