Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 258
Daniel Talamas Avatar asked Nov 07 '12 01:11

Daniel Talamas


2 Answers

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

like image 40
NPE Avatar answered Oct 13 '22 02:10

NPE


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.

like image 118
chris Avatar answered Oct 13 '22 02:10

chris