cannot pass objects of non-trivially-copyable type through '...'
Question:
I have a string I am trying to print. when I used cout, it outputs perfectly but using printf leaves it mangled.
Here is the code:
Sorry if this is a dumb question. I am doing my best to learn. Thank you for your time.
Here is the code:
int main ( int argc, char *argv[] )
{
// Check to make sure there is a single argument
if ( argc != 2 )
{
cout<<"usage: "<< argv[0] <<" <filename>\n";
return 1;
}
// Grab the filename and remove the extension
std::string filename(argv[1]);
int lastindex = filename.find_last_of(".");
std::string rawname = filename.substr(0, lastindex);
cout << "rawname:" << rawname << endl;
printf("rawname: %s", rawname);
}
The cout gives me "rawname: file"
The printf gives me "rawname: " and then a bunch of squiggly charactersSorry if this is a dumb question. I am doing my best to learn. Thank you for your time.
Solution:
it's because rawname is defined as a std::string. You need to use
The reason is that printf with the %s is expecting a null terminated C string in memory. Whereas a std::string stl string isn't exactly raw - it eventually null terminates in your situation, not sure if that's even a guarantee, since the length is internally managed by stl container class.
Edit:
As pointed out in a comment, internally it's guaranteed to be null terminated. So what you're seeing as 'squiggly lines' is an output of all the allocated but not utilized (or initialized) memory in that string up until the null terminator character.
printf("rawname: %s", rawname.c_str());
The reason is that printf with the %s is expecting a null terminated C string in memory. Whereas a std::string stl string isn't exactly raw - it eventually null terminates in your situation, not sure if that's even a guarantee, since the length is internally managed by stl container class.
Edit:
As pointed out in a comment, internally it's guaranteed to be null terminated. So what you're seeing as 'squiggly lines' is an output of all the allocated but not utilized (or initialized) memory in that string up until the null terminator character.
Comments
Post a Comment