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

标签 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.lower_bound(5);
    cout<<(*it).second<<endl;    // No problem
    printf("%s\n",(*it).second); // Run-time error
    return 0;
}

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

最佳答案

您正在将 std::string 传递给需要 char * 的内容(正如您在 printf 上的文档中看到的那样) >,这是一个 C 函数,没有类,更不用说 string)。要访问底层 char * 的 const 版本,请使用 c_str 函数:

printf("%s\n",(*it).second.c_str());

此外,(*i​​t).second 等同于 it->second,但后者更易于输入,而且在我看来,它更清楚是什么正在发生。

关于c++ - 为什么此代码使用带字符串的映射 (C++) 会出现运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13261958/

相关文章:

c++ - 在两个文件中查找不同的字符串 - C++

c++ - 使用 fscanf 时防止缓冲区溢出

php - 如何在 php 中对字符串求和?

c++ - 简单,但找不到 : syntax to work with member variables of STL queues with type class

c++ - 如何计算 std::basic_string<TCHAR>

c++ - 枚举指针的丢失值

arrays - 拆分不起作用excel VBA

java - 拆分字符串与另一个字符串不匹配

c++ - std::enable_if<> 错误

c++ - 意外的分割错误