为什么此代码使用带有字符串(C )的MAP具有运行时错误

Why this code has a runtime error using map with strings (C++)?

本文关键字:MAP 运行时错误 字符串 代码 为什么      更新时间:2023-10-16

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

#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,因此无法诊断此问题(尽管好的编译器可能会警告您此错误)。