可能有一个函数采用设置长度的char数组?

时间:2015-03-03 06:45:37

标签: c++ arduino

我试图为我的Arduino游戏保留一个高分表,并使用以下方法添加新的高分。问题是names被声明为names[positions][4],因此每个名称应该是三个字符或者谁知道可能会发生什么。我是否需要在函数中手动检查它,或者我可以在定义中强制执行它,还是应该使用完全不同的方法?

void Highscore::add(uint8_t score, const char * name)
{
    position = Highscore::getPosition(score);

    if (position >= positions) {
        return;
    }

    for (int i=positions-1; i<=position; i--) {
        scores[i] = scores[i-1];
        names[i] = names[i-1];
    }

    scores[position] = score;
    names[position] = name;

    Highscore::save();
}

1 个答案:

答案 0 :(得分:0)

问题是存储为char数组的c字符串不能被复制,按值参数传递,或者像内置标量类型那样进行比较。

解决方案1:使用 string 而不是char[4]这是推荐的C ++方式。它们极其简单易用,并且没有实际长度限制。但是如果你想限制它们的长度,你可以在用户输入时控制它。

解决方案2:如果您不能使用解决方案1,由于嵌入式系统的技术限制,您可以使用结构/类来保存字符串。这是一个模板化的版本:

template <int N>
struct fstring {
    char s[N+1];                // fixed string
    fstring() : s{} {}          // create an empty string
    fstring(const char*st) {    // convert a c-string to a fixed string
        strncpy(s, st, N);
        s[N] = 0;
    }
    bool operator== (fstring x) // compare two strings 
    {
        return strncmp(s, x.s, N) == 0;
    }
};
... 
fstring<3> names[10];  // ten fixed strings

解决方案3 :您可以完全按原样保留数据结构,但使用strncpy()代替分配,strcmp()代替比较。