-3

我在 C++ 中使用pdcurses来编写游戏,并且在尝试输出字符串时遇到了一些问题。

基本上相关的程序是这样的:

class Bunny {
private:
    string name;
public:
    string bgetname() { return name;};
}

class Troop {
private:
    vector<Bunny> bunpointer;  // bunpointer is a pointer to different bunnies
public:
    string getname(int i) {return bunpointer[i].bgetname();};
}

/* I create some bunnies in the troop which is pointed by bunpointer
 * troop is in class Troop
 */

int main() {
    Troop troop; // there will be 5 bunnies in the troop at the beginning
    initscr();
    // .....

    mvprintw(17,0,"%s was created!",troop.getname(1)); // <---- where problem is

    // .....
}

该程序应该输出部队中兔子的名字,但它实际上输出了一些随机字符,如<oru@....

我的猜测是troop.getnameinmain()可能在指向存储兔子名称的正确内存方面存在一些问题,因此输出是一些不规则字符。但我不明白为什么,因为我觉得链条mvprintw---> troop.getname()--->bunpointer.bgetname很简单......

4

1 回答 1

1

我从未使用过 pdcurses,但看起来 mvprintw 类似于 printf。所以 %s 意味着你传递给它一个 c 风格的字符串 (const char*),但是你给它一个 std::string。尝试在 std::string 上调用 c_str 函数:

mvprintw(17,0,"%s was created!",troop.getname(1).c_str());
于 2014-05-17T19:21:33.933 回答