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:
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 characters
The main difference is that printf() is used to send formated string to the standard output, while cout doesn't let you do the same, if you are doing some program serious, you should be using printf(). As pointed out above, printf is a function, cout an object.
To answer your question, printf is faster.
The C++ printf() function is usually used in C programming but can also run in C++.
cin and cout are streams and do not exist in C. You can use printf() and scanf() in C.
it's because rawname is defined as a std::string. You need to use
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With