在C++中,ostringstream是一個類,用于將數據以字符串的形式進行格式化輸出。它是iostream庫中的一個子類,用于將各種類型的數據轉化為字符串。
使用ostringstream時,需要包含頭文件
常見的ostringstream用法如下:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int num = 10;
double pi = 3.14159;
string name = "John";
ostringstream oss;
oss << "Number: " << num << ", PI: " << pi << ", Name: " << name;
string result = oss.str();
cout << result << endl;
return 0;
}
輸出:
Number: 10, PI: 3.14159, Name: John
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int num = 10;
ostringstream oss;
oss << "Number: " << num;
string result = oss.str();
cout << result << endl;
oss.str(""); // 清空字符串
oss << "New Number: " << num * 2;
result = oss.str();
cout << result << endl;
return 0;
}
輸出:
Number: 10
New Number: 20
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string str = "10 3.14159 John";
istringstream iss(str);
int num;
double pi;
string name;
iss >> num >> pi >> name;
cout << "Number: " << num << endl;
cout << "PI: " << pi << endl;
cout << "Name: " << name << endl;
return 0;
}
輸出:
Number: 10
PI: 3.14159
Name: John
這些是ostringstream的一些常見用法,可以根據具體的需求進行靈活運用。