printf打印字符串报错:cannot pass objects of non-trivially-copyable type
main.cpp:8:14: error: cannot pass objects of non-trivially-copyable type ‘std::string {aka class std::basic_string<char>}’ through ‘...’
printf("%s",s);
^
main.cpp:8:14: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘std::string {aka std::basic_string<char>}’ [-Wformat=]
这个错误和警告信息指出在 main.cpp 文件的第 8 行,你尝试使用 printf 函数以一个 char* 类型的参数去格式化输出一个 std::string 对象。但是,std::string 类型并不是一个平凡可复制的类型(non-trivially-copyable),这意味着它不能直接通过 printf 函数的 %s 格式说明符来传递。
错误和警告的原因是 printf 期望第二个参数是一个 char* 类型的指针,而 std::string 是一个类类型。%s 格式说明符用于输出以 null 结尾的字符串,这是 C 风格字符串的表示方式。
要解决这个问题,你可以采取以下几种方法之一:
-
使用
.c_str()方法:std::string类型提供了.c_str()方法,它返回一个指向以 null 结尾的字符数组的指针,这个数组是与std::string对象的内容相同的。使用.c_str()可以这样写:printf("%s", s.c_str());
-
使用
std::string的.data()方法:这个方法与.c_str()类似,也返回一个指向字符数据的指针:printf("%s", s.data());
-
使用 C++ 标准库函数:如果你使用的是 C++,可以考虑使用 C++ 标准库中的函数,如
std::cout和插入运算符<<,来输出std::string对象:std::cout << s << std::endl;

浙公网安备 33010602011771号