string str = "hello,world";
for (int i = 0; i < str.size(); ++i)
toupper(str[i]); // 返回值丟棄
cout << str; // 仍輸出 hello,world
`toupper(int c)` 返回轉換後的字符 (int),**不修改原參數**。必須接收返回值並賦回。
for (int i = 0; i < str.size(); ++i)
str[i] = toupper(str[i]); // 賦值回字符串
// 或 C++11 範圍 for
for (char &c : str) c = toupper(c);
#include
#include
#include
using namespace std;
int main() {
string str = "hello,world";
for (char &c : str) c = toupper(c);
cout << str << endl; // HELLO,WORLD
return 0;
}