今天在学C++容器中的vector,书后面有个练习题:
从cin读入一组词并把它们存入一个vector对象,然后设法把所有词都改写成大写的形式。输出改变后的结果,每个词占一行。
然后我的第一想法是这样的:
#include<iostream>
#include<string>
#include<ctype.h>
#include<vector>
using namespace std;
int main(void)
{
string word;
vector<string> str;
int i=0;
while(cin>>word)
str.push_back(word);
for(decltype(str.size()) index = 0;index != str.size();++index)
{
str[index] = toupper(str[index]);
}
cout<<str<<endl;
return 0;
}
当然这个程序错误百出,是个错误的示范,上面的程序学string对象时是可以实现的,但是vector不同于string,是不可能用同一种方法实现的。
错误一:这样用for循环遍历vector对象
错误二:就算上面的for循环遍历成功,用toupper把一整个string对象转为大写也是不可行的,toupper一次只能转换一个字符
错误三:直接用cin简单粗暴的输出vector对象
正确演示(来自与C++ Prime习题解答):
#include<iostream>
#include<string>
#include<ctype.h>
#include<vector>
using namespace std;
int main(void)
{
string str;
vector<string> vec;
char cont = 'y';
cout<<"请输入第一个词:"<<endl;
while(cin>>str)
{
vec.push_back(str);
cout<<"你要继续吗?(y or n)"<<endl;
cin>>cont;
if(cont != 'y'&& cont != 'Y')
break;
cout<<"请输入下一个词:"<<endl;
}
cout<<"转换后的结果是:"<<endl;
for(auto &mem:vec) //使用范围for循环语句遍历vec中的每个元素
{
for(auto &c : mem) //使用范围for循环语句遍历mem中的每个字符
c = toupper(c); //改写为大写字母形式
cout<<mem<<endl;
}
return 0;
}
下面是程序允许演示: