Help with Run-time error using map and printf C++

c-plus-plus
map
printf
stl
string

#1

Why does this code has a run-time error?

#include <cstdio>
#include <map>
#include <string>
#include <iostream>

using namespace std;
map <int, string> A;
map <int, string>::iterator it;

int main(){
    A[5]="yes";
    A[7]="no";
    it=A.lower_bound(5);
    cout<<(*it).second<<endl;    // No problem
    printf("%s

",(*it).second); // Run-time error
return 0;
}

Thanks!


#2

This is because printf("%s") expects a C-style string, not std::string

To fix it

  1. Use cout as it is much safer than printf, and can handle your own types (if you have overloaded operator<< for std::ostream)

  2. Or if you want to do it using printf, you can do A[5].c_str() to obtain C-style string.

    printf("%s", (*it).second.c_str()); //works


#3

So we have the answer, but not the question… What was it ?