Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting different output with printf and cout - C++

Tags:

c++

string

printf

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

like image 206
Scrimshaw Rest Avatar asked Jun 21 '11 01:06

Scrimshaw Rest


People also ask

Is printf the same as cout in C++?

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.

Is cout faster than printf?

To answer your question, printf is faster.

Can you use printf in C++?

The C++ printf() function is usually used in C programming but can also run in C++.

Does cout work in C?

cin and cout are streams and do not exist in C. You can use printf() and scanf() in C.


1 Answers

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.

like image 155
Nektarios Avatar answered Oct 11 '22 08:10

Nektarios