//编写一段程序,用cin读入一组整数并把他们存入一个vector对象
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v_int;
int i; //记录用户的输入值
char cont = 'y';
cout << "请输入第一个整数值: " << endl;
while (cin >> i)
{
v_int.push_back(i);
cout << "您要继续吗(y or n )? " << endl;
cin >> cont;
if (cont == 'y' || cont == 'Y')
cout << "请输入下一个整数值: " << endl;
else
break;
}
//使用范围for遍历每个v_int中的每个元素
for (auto c : v_int)
cout << c << " "; //依次输出对应数值
cout << endl;
system("pause");
return 0;
}
//改写上面的程序,现在读入的是字符串
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
vector<string> v_string;
string s;
//定义用户交互,决定是否继续输入
char cont = 'y';
//提示用户输入第一个字符串
cout << "请输入第一个字符串: " << endl;
//检测输入流
while (cin >> s)
{
v_string.push_back(s); //向vcetor对象中添加元素
//提示用户是否继续输入
cout << "您要继续吗(y or n)?" << endl;
cin >> cont;
//判断用户选择是否继续输入值
if (cont == 'y' || cont == 'Y')
cout << "请输入下一个字符串: " << endl;
//否则,则退出
else
break;
}
//打印vector对象的字符串
for (auto c : v_string)
cout << c << " " ;
cout << endl;
system("pause");
return 0;
}