Wednesday, April 6, 2011

Concat strings and numbers in C++?

I'm trying to concat "(" + mouseX + ", " + mouseY ")". However, mouseX and mouseY are ints, so I tried using a stringstream as follows:

std::stringstream pos;
pos << "(" <<  mouseX << ", " << mouseY << ")";
_glutBitmapString(GLUT_BITMAP_HELVETICA_12, pos.str());

And it doesn't seem to work.

I get the following error:

mouse.cpp:75: error: cannot convert std::basic_string<char, std::char_traits<char>, std::allocator<char> >' to const char*' for argument 2' to void glutBitmapString(void, const char*)'

What am I doing wrong in this basic string + integer concatenation?

From stackoverflow
  • Try

    _glutBitmapString(GLUT_BITMAP_HELVETICA_12, pos.str().c_str());
    
    Evan Teran : why the downvote? this answer is perfectly reasonable.
    KingNestor : @Evan Teran, I think the downvote came because before the edit he had a slight mistype? I upvoted though!
  • glutBitmapString() expects a char* and you're sending it a string. use .c_str() on the string like so:

    _glutBitmapString(GLUT_BITMAP_HELVETICA_12, pos.str().c_str());
    
    Tom : pedantic, but it's really expecting a "const char *". If it wanted "char *", .c_str() wouldn't work without a const_cast
    Evan Teran : @Tom: the prototype asks for a const char *, so I am not sure why that needed to be mentioned.

0 comments:

Post a Comment