1.编写一段程序,用cin读入一组整数并把它们存入一个vector对象。
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char const *argv[])
{
vector<int> v;
int x=0;
while(cin>>x){
v.push_back(x);
char y='y';
cout<<"要继续吗?输入n退出,输入其他字符继续。"<<endl;
cin>>y;
if(y=='n')
break;
}
for(auto c:v)
cout<<c<<endl;
return 0;
}
以上的程序中,单个输入整型数据,通过循环中的判断来控制输入。
- 改写第一题,这次读入字符串。
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char const *argv[])
{
vector<string> v;
string x="";
while(cin>>x){
v.push_back(x);
char y='y';
cout<<"要继续吗?输入n退出,输入其他字符继续。"<<endl;
cin>>y;
if(y=='n')
break;
}
for(auto c:v)
cout<<c<<endl;
return 0;
}
将容器改为字符串容器即可。
输出的结果
what
要继续吗?输入n退出,输入其他字符继续。
y
is
要继续吗?输入n退出,输入其他字符继续。
y
your
要继续吗?输入n退出,输入其他字符继续。
y
name
要继续吗?输入n退出,输入其他字符继续。
n
what
is
your
name
- 读入一组词,并将所有词改成大写形式。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
vector<string> v;
string x="";
while(cin>>x){
v.push_back(x);
char y='y';
cout<<"要继续吗?输入n退出,输入其他字符继续。"<<endl;
cin>>y;
if(y=='n')
break;
}
for(auto &c:v){
for(auto &s:c)
s=toupper(s);
cout<<c<<endl;
}
return 0;
}
这里面有对大写函数toupper(char ch)函数的应用,函数参数应为char类型,不能直接将string类型的数据传入,应当把每个string再拆分成char之后再使用toupper函数。
what
要继续吗?输入n退出,输入其他字符继续。
y
is
要继续吗?输入n退出,输入其他字符继续。
y
your
要继续吗?输入n退出,输入其他字符继续。
y
name
要继续吗?输入n退出,输入其他字符继续。
n
WHAT
IS
YOUR
NAME
--------------------------------
Process exited with return value 0
Press any key to continue . . .
- 读入一组整数并把它们存入一个vector对象,将每对相邻整数的和输出。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
vector<int> v;
int x=0;
while(cin>>x){
v.push_back(x);
}
for(decltype(v.size()) i=0;i<v.size()-1;i+=2){
cout<<v[i]+v[i+1]<<" ";
}
if(v.size()%2!=0)
cout<<v[v.size()-1];
return 0;
}
采用下标访问vector元素也很方便。这里的“^Z”表示按下了Ctrl+Z来终止输入。
测试结果1:
2 6 5 8 2 3
^Z
8 13 5
--------------------------------
Process exited with return value 0
Press any key to continue . . .
测试结果2:
7 6 4 4 5^Z
13 8 5
--------------------------------
Process exited with return value 0
Press any key to continue . . .
改编:将首尾元素相加的值输出。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
vector<int> v;
int x=0;
while(cin>>x){
v.push_back(x);
}
for(decltype(v.size()) i=0;i<v.size()/2;i++){
cout<<(v[i]+v[v.size()-1-i])<<" ";
}
if(v.size()%2!=0)
cout<<v[v.size()/2];
return 0;
}
结果:
1. 输入的数字个数为奇数。
4 7 3 9 2^Z
6 16 3
--------------------------------
Process exited with return value 0
Press any key to continue . . .
2. 输入的数字个数为偶数。
2 3 9 3 2 1
^Z
3 5 12
--------------------------------
Process exited with return value 0
Press any key to continue . . .