c++ primer 课后习题个人解答 part1 3.3

来源:互联网 发布:网络怎么赚钱? 编辑:程序博客网 时间:2024/06/10 20:17

读入一段文本到 vector 对象,每个单词存储为 vector 中的一个元素。把 vector 对象中每个单词转化为大写字母。输出 vector 对象中转化后的元素,每八个单词为一行输出。

 

看起来简单,做起来郁闷。

要注意的是:1.读入的字符串如果中间有空格,会自动算为多个词存到vector中。

2.小写转大写的函数,转换整个字符串的函数涉及到指针,暂时不会用,用的是toupper函数,每个单词依次转,toupper的函数返回值不能直接cout输出,要用char来接收,要不然直接输出的是数字。 至于 toupper 和_toupper函数的区别暂时不知道,好像只是兼容性不一样?参见http://msdn.microsoft.com/en-us/library/45119yx3(VS.80).aspx

 

#include "stdafx.h"#include <iostream>#include <string>#include <vector>using std::cin;using std::cout;using std::string;using std::vector;using std::endl;int _tmain(int argc, _TCHAR* argv[]){vector<string> words;string tempstr;while(cin>>tempstr){words.push_back(tempstr);}char tempchar;for(vector<string>::size_type ix=0;ix<words.size();ix++){for(int i=0;i<words[ix].size();i++){tempchar=_toupper(words[ix][i]);cout<<tempchar;}if((ix+1)%8==0))cout<<endl;}system("pause");return 0;}

查看标准答案 ,大同小异。 在遍历 words[ix] 的时候,标准答案用的是string::size_type,这个比我的要好。
原创粉丝点击