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!
Use c_str()
:
printf("%s\n",(*it).second.c_str());
printf()
is expecting a C string for %s
, and you're giving it a C++ string instead.
Since printf()
is not typesafe, it has no way of diagnosing this (although a good compiler might warn you about this error).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With