首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C++ toupper 函數使用錯誤:未將返回值賦回字符

     編輯:程式設計疑難解答

錯誤代碼


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;
}

注意

  • `toupper` 來自 ``,行為受當前 C locale 影響 (通常僅 ASCII 字母)。
  • 需轉換 `unsigned char` 避免負值未定義行為:`toupper(static_cast(c))`。
  • C++17 `std::to_upper` (實驗性) 或 Boost.Locale 處理 Unicode。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved