C++ 为什么此代码在使用带字符串的映射(C+;+;)时出现运行时错误?
为什么这段代码有运行时错误C++ 为什么此代码在使用带字符串的映射(C+;+;)时出现运行时错误?,c++,string,stl,map,printf,C++,String,Stl,Map,Printf,为什么这段代码有运行时错误 #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.l
#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
地图A;
对它进行迭代器;
int main(){
A[5]=“是”;
A[7]=“否”;
it=A.下界(5);
cout您正在将一个std::string
传递给需要一个char*
的对象(您可以从printf
的文档中看到,它是一个C函数,没有类,更不用说string
)。要访问基础char*
的常量版本,请使用c_str
功能:
printf("%s\n",(*it).second.c_str());
另外,(*it).second
相当于it->second
,但后者更容易键入,而且在我看来,它更清楚地显示了正在发生的事情。使用c_str()
:
<代码> Prtff()/Cuth>希望得到一个C代码,用于<代码> %s>代码>,而您给它一个C++字符串。
由于printf()
不是类型安全的,因此它无法诊断此问题(尽管一个好的编译器可能会警告您此错误)。g++4.6.3在编译时抱怨“错误:无法通过“…”传递非普通可复制类型“struct std::basic_string”的对象。”。我打赌你的编译器至少也有一个相关的警告。c_str()到底做什么?P.S.回答得很好!@DanielTalamas,std::string
有一个char*
数据成员,它用来存储字符串。c_str()
返回该函数的常量、以null结尾的版本,但它只有在调用下一个非常量成员函数之前才有效。正如名称所示,它从std::string
中提取一个C样式的字符串。C_str()到底做了什么?P.s.回答不错
printf("%s\n",(*it).second.c_str());