问题描述:
使用 printf 输出 string 类型的字符串,错误示例:
#include<stdio.h>
#include<iostream>
using namespace std;
string s;
int main()
{
string a = "I am a idiot.";
printf("%s",a);
return 0;
}
错误提示:
cannot pass non-POD object of type 'std::__1::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') to variadic function; expected type from format string was 'char *' [-Wnon-pod-varargs]
原因:
-
printf 函数输出字符串是针对 char* 的,即 printf 只能输出 c 语言的内置数据类型,而 string 不是 c 语言的内置数据类型
-
输出 string 对象中的字符串,可以使用 string 的成员函数 c_str() ,该函数返回字符串的首字符的地址
解决方案:
#include<stdio.h>
#include<iostream>
#include<string.h>
using namespace std;
string s;
int main()
{
string a = "I am a idiot.";
printf("%s",a.c_str());
return 0;
}