getline简单例子

瞅一眼c++98的getline(Get line from stream into string):
(1) istream& getline (istream& is, string& str, char delim);
(2) istream& getline (istream& is, string& str);
Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline character, ‘\n’, for (2)).
从 流is中取出字符串,保存到str中,直到限定符被发现或者对于(2)是‘\n’被发现。
那我们试一下:头文件《sstream》
1.用cin作为输入流,以 ‘\n’ 为结束符

	string tep;
	cout<<"输入点东西"<<endl; 
	getline(cin,tep);
	cout<<tep;

在这里插入图片描述
2.用cin 作为输入流,以 ‘/’ 作为限定符。

	string tep;
	cout<<"输入点东西"<<endl; 
	getline(cin,tep,'/');
	cout<<"输出为"<<endl; 
	cout<<tep;	

在这里插入图片描述
输入一行,输出一行,直到遇到了限定符‘/’为止。限定符之后的不会输出。
3.cin循环输入

无论while(getline(cin,tep,'/'))
还是 while(getline(cin,tep))都没有发现能跳出循环的条件。
自己只会在循环里面特别判断在跳出循环。
比如 if(tep=="/") break;

4.其他流
如stringstream为string流,istringstream和ostringstream分别是字符串输入、输出流。

	string tep="我是小米/我是大米米";
	stringstream st(tep);
	//或者可用 st.str(tep)
	string ans;
	getline(st,ans,'/');
	cout<<ans;

在这里插入图片描述


	string tep="/我是小米///我是大米米";
	stringstream st(tep);
	string ans;
	while(getline(st,ans,'/')){
		cout<<ans<<endl;
	}

在这里插入图片描述
读到了流的末尾,自动跳出了循环。"/我是小米///我是大米米",从左往右读。
比如读了“我是小米”在读发现是限定符,于是输出“我是小米”。注意会有空字符。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值