为什么此代码使用带有字符串(C )的MAP具有运行时错误
Why this code has a runtime error using map with strings (C++)?
为什么此代码有运行时错误?
#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("%sn",(*it).second); // Run-time error
return 0;
}
如果您使用COUT,则可以正常工作;但是,如果您使用printf会出现运行时错误。我该如何纠正?谢谢!
您将std::string
传递给期望char *
的东西(如您从printf
上的文档中看到的,它是C函数,它没有类,string
)。要访问基础char *
的const版本,请使用c_str
函数:
printf("%sn",(*it).second.c_str());
另外,(*it).second
等于it->second
,但后者更容易键入,我认为它更清楚地发生了。
使用c_str()
:
printf("%sn",(*it).second.c_str());
printf()
期望%s
的C字符串,而您将其提供给C 字符串。由于printf()
不是TypeAfe,因此无法诊断此问题(尽管好的编译器可能会警告您此错误)。
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 运行时错误:引用绑定到类型为"int"的空指针
- 为什么当 vector 为空时会显示运行时错误?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 运行时错误:矢量下标超出范围:正在检查空集
- 分配给gslice_array会导致运行时错误
- cout 新创建的对象引发运行时错误
- C++在使用std::multimap时出现运行时错误的几率很小
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 在 std::map 中使用结构作为值时出现运行时错误
- 使用MAP指针时运行时错误
- 为什么此代码使用带有字符串(C )的MAP具有运行时错误