Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么在将std::string传递给printf时会出现异常?_C++_String_Printf - Fatal编程技术网

C++ 为什么在将std::string传递给printf时会出现异常?

C++ 为什么在将std::string传递给printf时会出现异常?,c++,string,printf,C++,String,Printf,我不明白为什么会产生异常?这个程序主要尝试附加字符串。我在使用std::cout时得到了所需的输出,但在使用printf时没有得到。c\u str。必须使用此函数使用样式字符串。因为std::string与char const*不同,这是%s格式指定的。您需要使用c_str方法返回printf期望的指针: 更专业的是,printf是一个从C世界导入的函数,它需要一个C样式的字符串,一个指向以空字符结尾的字符序列的指针。ST::CYST:返回这样一个指针,以便C++字符串可以与现有的C函数一起使用

我不明白为什么会产生异常?这个程序主要尝试附加字符串。我在使用std::cout时得到了所需的输出,但在使用printf时没有得到。

c\u str。必须使用此函数使用样式字符串。

因为std::string与char const*不同,这是%s格式指定的。您需要使用c_str方法返回printf期望的指针:

更专业的是,printf是一个从C世界导入的函数,它需要一个C样式的字符串,一个指向以空字符结尾的字符序列的指针。ST::CYST:返回这样一个指针,以便C++字符串可以与现有的C函数一起使用。

Prtfs%s格式说明符期望C样式字符串不是STD::string,因此需要使用哪个返回conchchar *:< /p>


基本上,您已经知道printf将尝试访问参数,就像它是指向以null结尾的C样式字符串的指针一样。虽然这是C++,但是你应该只使用STD::CUT更安全。

P>Trpf处理C字符串char,你使用的是C++风格的字符串,因此需要在它们之间转换。 只需像这样使用c_str方法

printf("\n--------%s--------\n", str.c_str());

你需要使用STR.CSTR..得到……必须转换为C风格字符串……C++中你应该考虑使用CUT。与printf相比,它具有更好的编译时安全性。
printf("\n--------%s--------\n", str.c_str());
printf("\n--------%s--------\n", str.c_str());
printf("%s", str.c_str());