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::stringto something that expects achar *(as you can see from the documentation onprintf, which is a C function, which doesn’t have classes, let alonestring). To access a const version of the underlyingchar *, use thec_strfunction:Also,
(*it).secondis equivalent toit->second, but the latter is easier to type and, in my opinion, makes it clearer what’s happening.