c++ - Why do I get an exception when I pass a std::string to printf? -
this question has answer here:
- c++ printf std::string? 6 answers
#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 produces exception? program tries append strings. desired output when using std::cout
not when using printf
.
because std::string
not same char const *
, %s
format specifies. need use c_str()
method return pointer expected printf()
:
printf("\n--------%s--------\n", str.c_str());
to more technical, printf()
function imported c world , expects "c-style string" (a pointer sequence of characters terminated null character). std::string::c_str()
returns such pointer c++ strings can used existing c functions.
Comments
Post a Comment