为什么此代码使用带字符串的映射(C++)会出现运行时错误?

Dan*_*mas 6 c++ string printf stl map

为什么这段代码有运行时错误?

#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;
}
Run Code Online (Sandbox Code Playgroud)

如果你使用cout,它工作正常; 但是,如果使用printf,则会产生运行时错误.我该如何纠正?谢谢!

chr*_*ris 10

你正在传递一个std::string期望的东西char *(你可以从文档中看到printf,这是一个C函数,它没有类,更不用说了string).要访问底层的const版本char *,请使用以下c_str函数:

printf("%s\n",(*it).second.c_str());
Run Code Online (Sandbox Code Playgroud)

此外,(*it).second相当于it->second,但后者更容易打字,在我看来,更清楚地发生了什么.