stringstream是一個用于字符串操作的類,可以將各種數據類型轉換為字符串,也可以將字符串轉換為各種數據類型。下面是一些stringstream的常見用法:
#include <iostream>
#include <sstream>
int main() {
int num = 123;
double value = 3.14;
std::stringstream ss;
ss << "Integer: " << num << ", Double: " << value;
std::string str = ss.str();
std::cout << str << std::endl;
return 0;
}
#include <iostream>
#include <sstream>
int main() {
std::string str = "123 3.14";
int num;
double value;
std::stringstream ss(str);
ss >> num >> value;
std::cout << "Integer: " << num << ", Double: " << value << std::endl;
return 0;
}
#include <iostream>
#include <sstream>
int main() {
std::stringstream ss;
ss << "Hello, World!";
std::cout << ss.str() << std::endl;
ss.str("");
std::cout << ss.str() << std::endl; // Output is empty
return 0;
}
#include <iostream>
#include <sstream>
#include <iomanip>
int main() {
double value = 3.14159;
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << value;
std::string str = ss.str();
std::cout << "Formatted Value: " << str << std::endl;
return 0;
}
以上是stringstream的一些常見用法,可以根據實際需求靈活運用stringstream類進行字符串操作。