istringstream用法

istringstream对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。
#include<iostream>
#include<sstream>
using namespace std;
int main()
{
	string str, line;
	while(getline(cin, line))
	{
		istringstream stream(line);
		while(stream>>str)
			cout<<str.c_str()<<endl;
	}	
	return 0;
}
测试:
input:
abc df e efgeg ffg

ouput:
abc
df
e
efgeg
ffg

 

 

 

2010-09-03 12:41

"istringstream"

// <sstream>标准库中的"istringstream"类的使用
#include <iostream>
#include <sstream> //
using namespace std;#define Max 1000int main()
{
int i;
char S[ Max ];
//=================================================================
//(一)[声明的同时初始化]
printf("(一)[声明的同时初始化]:\n\n"); //(1)
printf("(1):\n");
double x;
while( gets(S) ) //gets函数允许输入的字符串中包含空格
{
istringstream ins1(S); ///在声明istringstream类对象ins的同时用字符串s将其初始化; for( i = 0; ins1 >> x; i++) ///pay attention here!!!
{
cout<<"x"<<i<<"="<<x<<endl;
}
} //-------------------------------- //(2)
printf("\n(2):\n");
char s[ Max ];
while( gets(S) ) //gets函数允许输入的字符串中包含空格
{
istringstream ins2(S); ///在声明istringstream类对象ins的同时用字符串s将其初始化; for( i = 0; ins2 >> s; i++) ///
{
cout<<"s"<<i<<"="<<s<<endl;
}
} //同样,istringstream类的对象也可以用于其他数据类型变量的输入,方法类似故不多说了... //------------------------------------ //(3)
printf("\n(3):\n");
//另外也可以直接用字符串常量初始化istringstream类对象: istringstream ins3("#123 1.23 aaa ,zzz kk,k oo.jjj"); char ch;
ins3>>ch;
cout<<ch<<endl;

int n;
ins3>>n;
cout<<n<<endl; float f;
ins3>>f;
cout<<f<<endl; char str[Max];
ins3>>str;
cout<<str<<endl; ins3.ignore(100, ',');
ins3>>str;
cout<<str<<endl; //=================================================================
//(二)[声明之后再用str()方法进行定向]: printf("\n\n\n(二)[声明之后再用str()方法进行定向]:\n\n"); istringstream iss1; / //(1)用字符串变量进行定向:
printf("\n(1):\n");
double y;
gets(S);
iss1.str(S);

for( i = 0; iss1 >> y; i++) //
{
cout<<"y"<<i<<"="<<y<<endl;
} //(2)用字符串常量进行定向:

printf("\n(2):\n");
istringstream iss2;
iss2.str("#123 1.23 aaa"); cout<<iss2.str()<<endl; ///查看流内容
//str()成员函数的使用可以让istringstream对象返回一个string字符串(例如这里的cout<<iss2.str();). iss2>>ch;
cout<<ch<<endl; iss2>>n;
cout<<n<<endl; iss2>>f;
cout<<f<<endl; iss2>>str;
cout<<str<<endl;

return 0;

 


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值