Daniel Talamas
Daniel Talamas

Reputation: 81

Why this code has a runtime error using map with strings (C++)?

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!

Upvotes: 6

Views: 2228

Answers (2)

NPE
NPE

Reputation: 500903

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).

Upvotes: 3

Qaz
Qaz

Reputation: 61970

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.

Upvotes: 10

Related Questions