【发布时间】:2017-06-24 05:04:50
【问题描述】:
我正在学习 C++ 的基础知识,并且正在尝试编写一个简单的函数,将给定输入中每个单词的每个字母大写。我写的:
#include <iostream>
#include <string>
#include <vector>
#include <cctype>
int main()
{
std::cout << "Please enter a sentence: ";
std::vector<std::string> words;
std::string x;
while (std::cin >> x) {
words.push_back((std::string) x);
}
std::cout << std::endl;
std::vector<std::string>::size_type size;
size = words.size();
for (int j = 0; j != size; j++) {
std::string &r = words[j];
for (int i = 0; i != r.length(); i++) {
r = toupper(r[i]);
std::cout << r << std::endl;
}
}
}
返回每个单词的首字母大写。比如我写hello world,程序返回:
H
W
谁能告诉我我做错了什么以及如何解决它。
【问题讨论】:
-
删除
(std::string)演员 - 它什么都不做。 -
我正在尝试编写一个简单的函数,将给定输入中每个单词的每个字母都大写 -- 如果您考虑学习算法函数“C++ 基础”,您可以简单地使用
std::transform(words[j].begin(), words[j].end(), words[j].begin(), toupper);而不是i循环。
标签: c++ function capitalize toupper