Q:

Why do I get an exception when I pass a std::string to printf?

#include<iostream>
#include<string.h>
#include<stdio.h>

using namespace std;

int main()
{
    char a[10] = "asd asd";
    char b[10] ="bsd bsd";
    string str(a);
    str.append(b);
    printf("\n--------%s--------\n", str);
    return 0;
}

I can't understand why this produces an exception? This program mainly tries to append strings. I get the desired output when using std::cout but not when using printf.

A:

Because std::string is not the same as char const *, which is what the %s format specifies.  You need to use the c_str() method to return the pointer expected by printf():
printf("\n--------%s--------\n", str.c_str());

To be more technical, printf() is a function imported from the C world and it expects a "C-style string" (a pointer to a sequence of characters terminated by a null character).  std::string::c_str() returns such a pointer so that C++ strings can be used with existing C functions.

