-3
#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.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Rahul Kushwaha
  • 421
  • 7
  • 14

4 Answers4

4

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.

cdhowie
  • 158,093
  • 24
  • 286
  • 300
1

c_str(). Have to use style string using this function..

Rahul Kushwaha
  • 421
  • 7
  • 14
1

printf() handles c strings (char *), you are using a c++-style string and therefore need to convert between them.

Simply use the c_str() method like so

printf("%s", str.c_str());
phyrrus9
  • 1,441
  • 11
  • 26
0

printfs %s format specifier is expecting a C style string not a std::string, so you need to use c_str() which return a const char*:

printf("\n--------%s--------\n", str.c_str());

Basically you have undefined behavior since printf will try to access your argument as if it was a pointer to a null terminated C style string. Although, since this is C++ you should just use std::cout is safer.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740