读入一段文本到vector对象,每个单词储存为一个vector中的一个元素,把vector中的每个元素的小写字母变成大写字母,输出vector转换后的元素,每八个单词为一行输出。
首先从标准输入端循环读入文本中的单词到string变量中直到遇到文件结束符,可以通过管道读取文本,也可以从终端敲入语句,用“Ctrl+D”结束。同时将读入的单词循环push_back到vector对象中。然后利用迭代器循环读取每个单词,同时利用cctype头文件中的toupper()函数将单词中的每个小写英文字母转换为大写。最后通过对8取余来判断是否换行并输出所有单词。
这里,我们在终端通过管道读入CppLive.com.txt文件中的文本,然后将转换后的结果按要求输出。用来测试的CppLive.com.txt中的内容如下:
I always needed time on my own I never thought I'd need you there when I cry And the days feel like years when I'm alone And the bed where you lie is made up on your side CppLive 编程在线
实现源代码:
/* CppLive_Vector_words.cpp */
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
int main(void)
{
  string str;
  vector<string> words;
  while (cin >> str)
  words.push_back(str);
  for (vector<string>::iterator iter = words.begin(); iter != words.end(); ++iter)
  {
    for (string::size_type i = 0; i != (*iter).size(); ++i)
      (*iter)[i] = toupper((*iter)[i]);
    if (iter != words.begin() && (iter - words.begin())%8 == 0)
    {
      cout << endl;
      cout << *iter << '\t';
    }
    else
      cout << *iter << '\t';
  }
  cout << endl;
  return 0;
}
编译:
g++ CppLive_Vector_words.cpp -o readWords
执行:
./readWords > ./CppLive.com.txt
输出:
I     ALWAYS  NEEDED TIME  ON    MY     OWN     I
NEVER THOUGHT I'D    NEED  YOU   THERE  WHEN    I
CRY   AND     THE    DAYS  FEEL  LIKE   YEARS   WHEN
I'M   ALONE   AND    THE   BED   WHERE  YOU     LIE
IS    MADE    UP     ON    YOUR  SIDE   CPPLIVE 编程在线
					除非注明,文章均为CppLive 编程在线原创,转载请注明出处,谢谢。



