Essential C++ 答案 第一章

1.5

(1)使用C-style字符串

#include<iostream>
#include<cstring>//<string.h>是不包括strlen的,要使用cstring
using namespace std;
int main()
{
	cout<<"what's your name:"<<endl;
	char name[100];
	cin>>name;
	int len=strlen(name);
	while(len<3){//strlen(name)需要头文件 #include<string.h>
		cout<<"please input your name again:"<<endl;
		cin>>name;
		len=strlen(name);
	}
	cout<<"thank you ! I got your name";
	return 0;
 }

(2)使用string

//使用string对象
 #include<iostream>
using namespace std;
int main()
{
	cout<<"what's your name:"<<endl;
	string name;
	cin>>name;
	while(name.size()<3){
		cout<<"please input your name again:"<<endl;
		cin>>name;
	}
	cout<<"thank you ! I got your name";
	return 0;
 }  

 

1.6

(1)使用vector

//使用vector
#include<iostream>
#include<vector>

#define max 50 
using namespace std;
int main()
{
	cout<<"请输入一串整数:"<<endl;
	vector<int>array;
 	char c=0;
	int i=0;
	int sum=0;
	int average=0;
	while((c=cin.get())!=('\n')){
		cin.unget();
		cin>>i;
		sum+=i;
		array.push_back(i);
	}
	cout<<sum<<endl;
	cout<<sum/array.size()<<endl;
	return 0;
 }

(2)使用array

//存放到array:array在定义时就要明确大小,这边取一个大点的数
#include<iostream>
#define max 50 
using namespace std;
int main()
{
	cout<<"请输入一串整数:"<<endl;
	int array[max];
	int c;
	int i=0;
	int sum=0;
	int average=0;
	for(;(c=cin.get())!=('\n');++i){
		cin.unget(); //如果读入的不是回车,把该流倒回去一位 
		cin>>array[i];
		sum+=array[i];
	}
	cout<<sum<<endl;
	cout<<sum/i<<endl;
	return 0;
 }  

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值