在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的一些常见用法,可以根据具体的需求进行灵活运用。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>