0
点赞
收藏
分享

微信扫一扫

c++中如何用vector与cin实现字符串的循环读取

gy2006_sw 2022-02-09 阅读 122

 

实际运用中我们不知道需要录入数据的次数及循环期望输入几个字符串,这时我们可以用c++中输入操作符“>>"进行多次读取。

vector因为有动态扩展性,可以作为一串数据的容器。而push_back()每次会添加一个元素到vector的末尾。再结合while及for即可写出一个简单的循环读取。


#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
	vector<string> strvec;
	string s;
	while (cin >> s)
	{
		strvec.push_back(s);
		for (int i = 0; i < strvec.size(); i++)
		{
			cout << strvec[i] << " ";
		}
		cout << endl;
	}
	return 0;
}

输入操作cin>>s的表达式可以反映当前是否有输入。键盘输入与文件输入有所不同这里不做解释。键盘输入结果如下:


​life
life
is
life is
so
life is so
simple
life is so simple
,
life is so simple ,
such as
life is so simple , such
life is so simple , such as
the
life is so simple , such as the
autumn.
life is so simple , such as the autumn.

我们可以看到程序反馈输出字符串vector中所有字符串,life is so simple,such as the autum.

举报

相关推荐

0 条评论