字符串 I/O 实现,定义于头文件
我们一般使用使用stringstream对象简化类型转换,准确的说,我们一般使用stringstream里面的运算符重载operator>>
提取带格式数据
我们这里提供一个使用方法
string到int的转换
string result=”10000”;
int n=0;
stream<>n;//n等于10000
如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要使用clear()方法;
在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的。
注:关于stream.clear()和stream.str(""),作用还不太清楚。又说clear是清除标志位,str("")是清楚stream内容的。但在多次转换过程是,的确是使用clear才准确,这是验证过的。
我们举一道题的例子
題目:输入的第一行有一个数字 N 代表接下來有 N 行資料,每一行資料里有不固定個數的整數(最多 20 個,每行最大 200 個字元),請你寫一個程式將每行的总和印出來。
输入:
3
1 2 3
20 17 23 54 77 60
111 222 333 444 555 666 777 888 999
输出:
6
251
4995
#include
#include
#include
using namespace std;
int main()
{
string str;
stringstream ss;
int n, i, sum, a;
cin >> n;
// getline遇到换行停止,所以我们不得不在输入n后,强制换行
getline(cin, str);
for (i=0; i> a;
if ( ss.fail() ) break;
sum+=a;
}
cout << sum << endl;
}
return 0;
}
#include
#include
#include
using namespace std;
int main()
{
int i=23412;
string str1("hhhhhh");
stringstream stream;
stream<>str1;//把stream的值给str1
cout<
#include
#include
#include
using namespace std;
int main()
{
char a[100]="hhhhhhhhh";
double k=3.1423;
stringstream stream;
stream<>a;
cout<
#include
#include
#include
using namespace std;
int main()
{
string str1("wo hao shuai a a a a ");
string a1,a2,a3,a4;
stringstream stream(str1);
stream>>a1;
stream>>a2;
stream>>a3;
stream>>a4;
cout<
Problem Description
输入一行数字,如果我们把这行数字中的‘5’都看成空格,那么就得到一行用空格分割的若干非负整数(可能有些整数以‘0’开头,这些头部的‘0’应该被忽略掉,除非这个整数就是由若干个‘0’组成的,这时这个整数就是0)。
你的任务是:对这些分割得到的整数,依从小到大的顺序排序输出。
Input
输入包含多组测试用例,每组输入数据只有一行数字(数字之间没有空格),这行数字的长度不大于1000。
输入数据保证:分割得到的非负整数不会大于100000000;输入数据不可能全由‘5’组成。
Output
对于每个测试用例,输出分割得到的整数排序的结果,相邻的两个整数之间用一个空格分开,每组输出占一行。
Sample Input
0051231232050775
Sample Output
0 77 12312320
#include
#include
#include
#include
using namespace std;
int a[10010];
int main()
{
string str;
stringstream stream;
int x,len;
while(cin>>str){
for(int i=0;i>a[x])
x++;
len=x;
sort(a,a+len);
for(int i=0;i