std::ostringstream
是 C++ 標(biāo)準(zhǔn)庫中的一個非常有用的類,它允許你使用流操作符 <<
來構(gòu)建字符串。以下是如何使用 std::ostringstream
來處理字符串流的一些基本示例:
std::ostringstream
拼接字符串#include <iostream>
#include <sstream>
#include <string>
int main() {
std::ostringstream oss;
oss << "Hello, " << "World!" << std::ends; // 注意 std::ends 用于添加空行
std::string str = oss.str(); // 使用 str() 方法獲取構(gòu)建好的字符串
std::cout << str << std::endl;
return 0;
}
std::ostringstream
中格式化字符串你可以使用流操作符 <<
來格式化字符串,就像在 printf
中一樣。
#include <iostream>
#include <sstream>
#include <string>
int main() {
int a = 10;
double b = 3.14;
std::ostringstream oss;
oss << "The value of a is "<< a << " and the value of b is " << b;
std::string str = oss.str();
std::cout << str << std::endl;
return 0;
}
std::ostringstream
進行類型轉(zhuǎn)換std::ostringstream
也可以用于不同類型之間的轉(zhuǎn)換。例如,你可以將一個整數(shù)轉(zhuǎn)換為字符串。
#include <iostream>
#include <sstream>
#include <string>
int main() {
int a = 123;
std::ostringstream oss;
oss << a;
std::string str = oss.str();
std::cout << "The string representation of "<< a << " is " << str << std::endl;
return 0;
}
std::ostringstream
進行多個操作你可以在一個 std::ostringstream
對象上執(zhí)行多個操作,然后再獲取構(gòu)建好的字符串。
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::ostringstream oss;
oss << "The answer is " << 42 << ", which is " << (100 - 42) << ".";
std::string str = oss.str();
std::cout << str << std::endl;
return 0;
}
這些示例展示了如何使用 std::ostringstream
來方便地構(gòu)建和處理字符串。