Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/jenkins/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么此代码在使用带字符串的映射(C+;+;)时出现运行时错误?_C++_String_Stl_Map_Printf - Fatal编程技术网

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());