Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.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++ 在C+中替换字符串中的字符+;_C++_C_Database_String - Fatal编程技术网

C++ 在C+中替换字符串中的字符+;

C++ 在C+中替换字符串中的字符+;,c++,c,database,string,C++,C,Database,String,在我的应用程序中,我将从数据库中检索错误消息字符串。我想在错误信息中替换数字。错误消息将是C样式的字符串,如: Message %d does not exist 或 理想情况下,我希望能够使用此语句执行C风格的printf,并在中替换我自己的数字。我知道我可以手动完成它,但是有没有一种更简单的方法来使用它,就像在普通的打印文件中使用字符串一样? < p> C++方式是使用STD::String Strue:< /P> std::stringstream str; str << "

在我的应用程序中,我将从数据库中检索错误消息字符串。我想在错误信息中替换数字。错误消息将是C样式的字符串,如:

Message %d does not exist


理想情况下,我希望能够使用此语句执行C风格的printf,并在中替换我自己的数字。我知道我可以手动完成它,但是有没有一种更简单的方法来使用它,就像在普通的打印文件中使用字符串一样?

< p> C++方式是使用STD::String Strue:< /P>
std::stringstream str;
str << "Message " << messageName << " doesn't exist";

std::string out = str.str();
和,其作用类似于printf,但完全是类型安全的,并支持所有用户定义的类型:

std::string out = format( "Message %1 doesn't exist" ) % "MyMessage";

除了简单的字符串连接或使用
从libc使用
sprintf()
有什么问题?@yan缓冲区溢出。最好至少使用
snprintf
如何使用sprintf来实现这一点?假设我将文本读入一个变量char*text=“Message%d不存在”我可以用它将文本打印到缓冲区,但我如何替换%d?@DavidBrown我不是指
sprintf()
,具体来说,我指的是
s*printf()
函数族。boost::format可能是最接近我所寻找的东西。谢谢
std::string message = "Message %s doesn't exist";
boost::replace_first( str, "%s", "MyMessage" );

// message == "Message MyMessage doesn't exist"
std::string out = format( "Message %1 doesn't exist" ) % "MyMessage";
int message_no=5;
std::cout << boost::format("Message %d doesn't exist") % message_no ;