簡體   English   中英

“表達式必須有類類型”但是在檢查類型時它確實有一個字符類?

[英]"expression must have class type" but when checking the type it does have a class of char?

我只是為 C++ 做一個簡單的編碼挑戰,因為我對這門語言比較陌生,我想按字典順序比較兩個字符串,以便在輸入的第一個字符串在字典上比第二個字符串大時打印出 1,並且如果相反,則打印出 -1。 當我循環時,我只想以小寫形式比較它們,所以如果第一個字符串中的一個字符是大寫的“A”,我想把它變成小寫的“a”,同樣的規則適用於每個被比較的兩個字符串的字符。 當我嘗試在我的if語句中使用像這樣的<cctype>標頭實現這個想法時... first_str[i].tolower()和第二個字符串相同,我收到錯誤“表達式必須具有類類型”。 這是我的代碼:

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main() {

    int first{};
    int second{};

    string first_str{};
    string second_str{};

    cin >> first_str;
    cin >> second_str;


    for (size_t i{}; i < first_str.length(); ++i) {
        // The if statement below has one accessing the character by indexing with the square brackets
        // and the other one has it through the .at() method provided by the <string> header
        if (first_str[i].tolower() > second_str.at(i).tolower()) {
            ++first;
        } else if (first_str.at(i).tolower() < second_str.at(i).tolower()) {
            ++second;
        } else { // If they are equal then just add the count to both
            ++first;
            ++second;
        }
    }
    if (first > second)
        cout << 1 << endl;
    else if (first > second)
        cout << -1 << endl;
    else
        cout << 0 << endl;

    return 0;
}

我決定進一步調查但無濟於事,就像我說我是 C++ 的初學者一樣,當我遇到類似編譯錯誤的人時,答案會談論稱為指針的東西......我還沒有學到然而,所以很困惑。 我想知道我是否需要學習以了解為什么會發生這種情況,或者是否還有其他原因導致我的代碼中出現此問題。 我會盡快努力學習指針,感謝您閱讀我的問題。

這是因為 first_str[i] 是一個char Char 沒有.tolower()方法。

所以而不是:

first_str[i].tolower()

你應該使用:

tolower(first_str[i])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM