Search code examples
c++stringpdcurses

String Output in Pdcurses


I am using pdcurses in C++ to program a game and am having some problems when trying to output a string.

Basically the relevant program is like this:

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

    // .....
}

The program should output names of the bunnies in the troop, but it actually outputs some random characters like < or u or @....

My guess is that the troop.getname in main() may have some problems in pointing to the correct memory that stores the name of the bunnies, so the output are some irregular characters. But I cannot see why because I feel like the chain mvprintw--->troop.getname()--->bunpointer.bgetname is straightforward...


Solution

  • I've never used pdcurses but it looks like mvprintw is similar to printf. So the %s means you're passing it a c-style string (const char*), but you give it a std::string. Try calling the c_str function on your std::string:

    mvprintw(17,0,"%s was created!",troop.getname(1).c_str());