Why does this code have a run-time error using the card with strings (C ++)?

advertisements

Why does this code has a runtime 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\n",(*it).second); // Run-time error
    return 0;
}

If you use cout, it works fine; however, if you use printf it gives runtime error. How do I correct it? Thanks!


You're passing in a std::string to something that expects a char * (as you can see from the documentation on printf, which is a C function, which doesn't have classes, let alone string). To access a const version of the underlying char *, use the c_str function:

printf("%s\n",(*it).second.c_str());

Also, (*it).second is equivalent to it->second, but the latter is easier to type and, in my opinion, makes it clearer what's happening.