实际运用中我们不知道需要录入数据的次数及循环期望输入几个字符串,这时我们可以用c++中输入操作符“>>"进行多次读取。
vector因为有动态扩展性,可以作为一串数据的容器。而push_back()每次会添加一个元素到vector的末尾。再结合while及for即可写出一个简单的循环读取。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19#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的表达式可以反映当前是否有输入。键盘输入与文件输入有所不同这里不做解释。键盘输入结果如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19life 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.
最后
以上就是重要红酒最近收集整理的关于c++中如何用vector与cin实现字符串的循环读取的全部内容,更多相关c++中如何用vector与cin实现字符串内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复