問題:toupper(int) 僅接受單字符,不能直接作用於 std::string。需遍歷字符串每個字符調用 toupper。
vector<string> text{"hello world"};
for (auto it = text.begin(); it != text.end() && !it->empty(); ++it) {
*it = toupper(*it); // 編譯錯誤:無法將 string 轉為 int
cout << *it << endl;
}
#include <iostream>
#include <vector>
#include <string>
#include <cctype>
using namespace std;
string toUpper(const string& s) {
string r = s;
for (char& c : r) c = toupper(static_cast(c));
return r;
}
int main() {
vector text = {"hello world", "c++ primer"};
for (auto it = text.begin(); it != text.end() && !it->empty(); ++it) {
cout << toUpper(*it) << endl;
}
return 0;
}
toupper 參數為 int (實際為 unsigned char 或 EOF),返回轉換後的 int。static_cast(c) 避免負值導致未定義行為 (針對非 ASCII 字符)。#include <ranges>
#include <algorithm>
for (auto& s : text | views::take_while([](auto& x){ return !x.empty(); })) {
ranges::transform(s, s.begin(), [](char c){ return toupper((unsigned char)c); });
cout << s << endl;
}
!it->empty() 報錯若 text 類型改為 string (而非 vector),則 it 是 char 迭代器,it->empty() 無意義 (char 無 empty() 方法)。string 本身用 text.empty() 判斷整體是否為空。
理解迭代器指向的元素類型,才能正確調用成員函數。