I've been programming in C++ for about a year now, and I've run into a strange issue. I've found a workaround for the issue, but I want to understand what caused the issue in the first place.
I am using a string to pass a value to a function that requires a char*. So, the function call looks something like this:
1 2 3
int i = 2;
string foo = "foo bar baz " + i;
function(stuff,stuff,stuff,(char*)foo.c_str(),stuff,stuff);
Don't worry about what "stuff" is, that is all functional.
Now, when the function displays my string, it is missing the first 4 characters. It's easy enough to work around, I just placed 4 spaces before "foo". Obviously, this is not ideal.
I am still not a master of pointers, so I was wondering if that might be the issue? Or what are some other reasons this could happen?
Actually, in my real code, i is 4. I didn't think that was relevant, so I didn't include that. Glad to have an explanation that makes sense, thank you vlad!
I do need to have the integer in there, so how should I work around this? I'm trying to see if I can do something with foo.append(""+i); with no success.
I do everything like that using stringstreams. Can throw whatever you want in there and have it give you a nice string. I believe this is the standard C++ way of doing things.
stringstreams are always handy. I'm actually in the process of re-writing a 2000 line X-Plane plugin, and stringstreams are what I used in the original code. I'm trying to optimize the new code, so that's why I asked. But, if stringstreams are the standard, then I'll use them again.
string foo = "foo bar baz " + std::to_string( i );
Only you should take into account that MS VC++ 2010 does not contain the overload function std::to_string for the argument of type int. So you could use std::to_string( static_cast<long long>( i ) ) if you are using MS VC++ 2010
Once again, thank you vlad. As I said, I'm trying to optimize the new code, and it would seem to me that the overhead from the to_string function is probably less than that of a stringstream, so I'm going with that.
Don't quote me on this, but I think the performance of stringstream is pretty solid. I used it for a time-sensitive project awhile back and did it well. Faster than a manual conversion
EDIT:
After some research, it appears my results were the minority.