ostringstream is a class in the C standard library that can be used to build strings. It is an output stream and can be used like cout, but the output results will not be displayed in the terminal, but saved. in a string object. When you need to build a string, you can use ostringstream to operate, which is very useful in formatted output, logging, etc.
ostringstream is a class in the C standard library, which belongs to the
The following is the basic usage of ostringstream:
#include <sstream> #include <iostream> #include <string> int main() { // 创建一个ostringstream对象 std::ostringstream oss; // 向ostringstream对象中插入数据 oss << "Hello, " << "world!" << std::endl; // 将ostringstream对象转化为字符串 std::string str = oss.str(); // 输出字符串 std::cout << str; return 0; }
In this example, we first create an ostringstream object, and then use it like cout to insert data. Inserted data includes strings and newlines. Then, we use the str() method to convert the ostringstream object into a string, and finally output the string to the terminal.
After running this code, the terminal will output:
Hello, world!
In addition to using the << operator to insert data into the ostringstream object, you can also use the method oss.write(char_array, size_t ), which writes a character array to an ostringstream object. This method requires two parameters, the first parameter is the character array to be written, and the second parameter is the number of bytes to be written. For example:
char arr[] = "Hello, world!"; oss.write(arr, sizeof(arr) - 1); // 第二个参数是-1,表示写入所有字符,不包括字符串结尾的null字符。
In addition, ostringstream also provides many other methods, such as: setf(), unsetf(), precision(), setiosflags(), etc., which can be used to set the output format. For example:
oss.setf(std::ios::fixed, std::ios::floatfield); // 设置浮点数格式为固定小数点格式。 oss.precision(2); // 设置精度为2。 oss << 3.14159265358979323846; // 输出3.14。
In general, ostringstream is a very useful tool that can be used to build strings. It is used very similar to cout, but the output result is saved in a string. rather than displayed in the terminal.
The above is the detailed content of Detailed explanation of ostringstream usage. For more information, please follow other related articles on the PHP Chinese website!