Maxbad`Blog

<sstream>流stream与其他数据类型转换

2020-11-17 · 1 min read
#include <iostream>
#include <string>
#include <sstream>
using namespace std; 
int main(int argc, char *argv[])
{
	stringstream stream;
	// 将string转换为int
	string text = "123456";
	stream << text;
	int n = 0;
	stream >> n;
	n++;
	cout << n << endl;
 
	text = "";
	// 注意这句clear必不可少,注释掉之后stream的<<操作无效
	stream.clear();									 // 试试看注释掉?
	// 将int转换为string
	stream << n;
	stream >> text;
	// 加一句hello方便区分
	text += "hello";
	cout << text << endl;
	system("pause");
	return 0;
}