【发布时间】:2015-04-11 02:00:14
【问题描述】:
对于这个问题:
从 cin 读取一系列单词并将值存储为向量。后 您已经阅读了所有单词,处理了向量并将每个单词更改为 大写。打印转换后的元素,一行八字
这段代码完成了练习:
#include <iostream>
#include <vector>
#include <string>
using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::string;
int main()
{
vector<string> vec;
string word;
while (cin >> word)
vec.push_back(word);
for (auto &str : vec)
for (auto &c : str)
c = toupper(c);
for (decltype(vec.size()) i=0; i != vec.size(); ++i)
{
if (i!=0&&i%8 == 0) cout << endl;
cout << vec[i] << " ";
}
cout << endl;
return 0;
}
我只是想知道为什么你必须在这个块中有两个循环范围:
for (auto &str : vec)
for (auto &c : str)
c = toupper(c);
...主动将向量的元素更改为大写,而不是这样:
for (auto &str : vec)
str = toupper(str);
【问题讨论】:
-
Documentation for
std::toupper。请注意,除了最底部列出的语言环境之外,没有其他重载。 -
你可以很容易地定义这样一个对字符串进行操作的函数,只要你不需要比基本的
toupper函数更多。主要是,直接使用它只适用于 ASCII 字符。对于一般国际字符支持,您需要使用宽文本,例如std::wstring.