stringstream c++流的使用

0.数据存入流

#include<iostream>
#include<string>
#include<cstdio>
#include<sstream>
using namespace std;
int main()
{
	stringstream stream;
	string str;
	cin >> str;
	//abc--abc
	//123 abc--123
	stream << str;
	cout << stream.str();
	return 0;
}
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
	stringstream stream;
	string str;
	getline(cin, str);
	//123 abc--123 abc
	stream << str;
	cout << stream.str();
	return 0;
}

1.类型转换

  • 数值转字符串
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
	int k;
	cin >> k;//3
	stringstream stream;
	stream << k;
	cout <<"stream:"<< stream.str()<<endl;
	cout << "k:" << k;
	return 0;
}

stream:3
k:3

  • 字符串转数值
#include<iostream>
#include<string>
#include<cstdio>
#include<sstream>
using namespace std;
int main()
{
	string str;
	stringstream stream;
	cin >> str;//123
	stream << str;
	int k;
	stream >> k;
	cout << "stream:" << stream.str() << endl;
	cout << "k:" << k << endl;
	return 0;
}

stream:123
k:123

#include<iostream>
#include<string>
#include<cstdio>
#include<sstream>
using namespace std;
int main()
{
	string str;
	cin >> str;//123.4
	istringstream i(str);
	double x;
	i >> x;
	cout << x << endl;
	cout << i.str() << endl;
	return 0;
}

123.4
123.4

2.多个字符串的连接+字符串的断开

#include<string>
#include<sstream>
#include<iostream>
using namespace std;
int main()
{
	stringstream stream;
	stream << "Hello"<<" "<< "World";
	stream << ",everyone";
	string str;
	getline(stream,str);
	cout << str << endl;
	//cout << stream.str();(和上面效果一样)
    //清空--stream.str("");
}

输出结果:
在这里插入图片描述

#include<string>
#include<sstream>
#include<iostream>
using namespace std;
int main() {
	int n;
	cin >> n;
	cin.ignore();
	string str;
	stringstream stream;
	for (int i = 0; i < n; i++)
	{
		getline(cin, str);
		stream.clear();//将数据插入流更新前需要清空
		stream << str;
		int sum = 0;
		int k;
		while (stream >> k)
		{
			sum += k;
		}
		cout << sum << endl;
	}
    return 0;
}
	

输出结果:
在这里插入图片描述

posted on 2021-07-12 15:01  不依法度  阅读(48)  评论(0)    收藏  举报

导航