sprintf的C ++等效项是什么?
该sprint()函数也存在于C和C++内部。此函数用于将某些内容存储在字符串中。语法就像printf()函数一样,唯一的区别是,我们必须在其中指定字符串。
同样在C++中,我们可以通过使用ostringstream进行相同的操作。此ostringstream基本上是输出字符串流。这存在于sstrem头文件中。让我们看看如何使用它。
示例
#include<iostream>
#include<sstream>
using namespace std;
int main() {
string my_str;
ostringstream os;
os << "This is a string. We will store " << 50 << " in it. We can store " << 52.32 << " also.";
my_str = os.str(); //now convert stream to my_str string
cout << my_str;
}输出结果
This is a string. We will store 50 in it. We can store 52.32 also.