正如许多其他答案已经说过的那样,std::toupper
传递给的参数并按值返回结果,这是有道理的,因为否则,您将无法调用std::toupper('a')
. 您不能'a'
就地修改文字。您也可能将输入放在只读缓冲区中,并希望将大写输出存储在另一个缓冲区中。所以按价值的方法要灵活得多。
另一方面,多余的是您检查isalpha
and islower
。如果该字符不是小写字母字符,toupper
则无论如何都会不理会它,因此逻辑简化为这一点。
#include <cctype>
#include <iostream>
int
main()
{
char text[] = "Please send me 400 $ worth of dark chocolate by Wednesday!";
for (auto s = text; *s != '\0'; ++s)
*s = std::toupper(*s);
std::cout << text << '\n';
}
如果您发现它更漂亮,您可以使用算法进一步消除原始循环。
#include <algorithm>
#include <cctype>
#include <iostream>
#include <utility>
int
main()
{
char text[] = "Please send me 400 $ worth of dark chocolate by Wednesday!";
std::transform(std::cbegin(text), std::cend(text), std::begin(text),
[](auto c){ return std::toupper(c); });
std::cout << text << '\n';
}