<C++ Primer_5th>习题_3.14

//编写一段程序,用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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值