在C++編程中,std::stringstream
是一個非常有用的類,它允許你將字符串視為流對象進行操作
包含頭文件:首先,確保你已經(jīng)包含了<sstream>
頭文件。
#include <sstream>
使用std::stringstream
進行字符串拼接:
std::stringstream ss;
ss << "Hello, " << "World!"<< std::endl;
std::string result = ss.str();
從字符串中提取數(shù)據(jù):
std::string input = "123 456 789";
std::stringstream ss(input);
int a, b, c;
ss >> a >> b >> c;
使用std::getline()
從字符串中按行讀取數(shù)據(jù):
std::string input = "Line 1\nLine 2\nLine 3";
std::stringstream ss(input);
std::string line;
while (std::getline(ss, line)) {
// Process the line
}
使用std::istringstream
和std::ostringstream
分別進行輸入和輸出操作:
std::istringstream iss("123 456 789");
int a, b, c;
iss >> a >> b >> c;
std::ostringstream oss;
oss << "Hello, " << "World!"<< std::endl;
std::string result = oss.str();
清空stringstream
:
std::stringstream ss;
// ... perform some operations ...
ss.str(""); // Clear the stringstream
ss.clear(); // Clear any error flags
使用std::stringstream
進行類型轉(zhuǎn)換:
int value = 123;
std::stringstream ss;
ss<< value;
std::string result = ss.str();
遵循這些最佳實踐,可以確保你在使用std::stringstream
時編寫高效、可維護的代碼。