为什么这段代码会出现运行时错误?
#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());
此外,(*it).second
等同于 it->second
,但后者更易于输入,而且在我看来,它更清楚是什么正在发生。
关于c++ - 为什么此代码使用带字符串的映射 (C++) 会出现运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13261958/