#54149: 關於 c++ 使用 isupper 時,有些人可以 AC,有些人卻會 WA 的原因


pofly (不挖鼻孔有害身心健康)


我找到問題了!!

isupper 依然能用,只是要注意返回值

可以比較一下這兩個版本的執行結果



版本1:

#include <iostream>
#include <cctype>

int main() {
    char a = 'A';
    char b = 'B';
    if (std::isupper(a) == std::isupper(b)) {
        std::cout << "true";
    } else {
        std::cout << "false";
    }
}

 

版本2:

#include <iostream>
#include <cctype>

int main() {
    char a = 'A';
    char b = 'B';
    bool a_bool = std::isupper(a);
    if (a_bool == std::isupper(b)) {
        std::cout << "true";
    } else {
        std::cout << "false";
    }
}

 

版本1 的執行結果是 true

版本2 的執行結果是 false

 

因為 isupper 的返回值並不是 bool,而是 int !!!

並且這個返回值在 GCC (Zerojudge 用的編譯器)的實作是返回常數

如果結果為真,會返回 unsigned char 的最大值 256 (bytes: 11111111)

如果結果為假,會返回 0

 

bool 在底層只有兩個數值 0 (byte: 00000000) 和 1 (bytes: 00000001)

 

所以版本1 的 std::isupper(a) == std::isupper(b) 最終會得到 true 的結果

版本2 實際上是在比較 1 == 256,於是就得到 false

 

如果想用版本2,可以改成 a_bool == (bool)std::isupper(b) 強制轉換型態,這樣就可以 AC 了

 

馬的 c++ 到處都是坑......