簡體   English   中英

檢查字符是否屬於數組(初級 C++)

[英]Checking if characters belong in an array (beginner C++)

我需要編寫一個程序,要求輸入三個字符,然后依次檢查第一個、第二個、第三個字符是否屬於字母表(小寫或大寫)。 到目前為止我所擁有的是這個

char v1, v2, v3;
cout << "Enter 3-character identifier: ";
cin >> v1 >> v2 >> v3;

if ((v1 != 'a')&&(v1!='b'))
    cout << v1 << v2 << v3 <<" is an invalid input, check first character\n";
else if (v2 != 'a')
    cout << v1 << v2 << v3 << "Invalid input, check second character\n";
else (v3 != 'a');
    cout << v1 << v2 << v3 << "Invalid input, check third character\n";

我正在測試是否可以通過詢問它是否不分別等於每個大小寫字母來將字符與字母進行比較,但這聽起來很糟糕,所以我停在了“b”處。 我似乎無法將字符與數組或字符串進行比較(顯示錯誤),這是我的 C++ 知識的范圍。 我似乎也無法使用“其他” function 僅在前兩個條件為假時應用。 非常感謝任何幫助!

你也可以使用isalpha() function 來做同樣的事情。 既然你提到你只經歷過if/else這樣的基本概念,你可以嘗試這種方式,我只使用 if/else 條件和isalpha() function 來連續檢查提供的輸入是否分別是字符或不是。

#include<iostream>
#include<cctype>

using namespace std;

int main()
{
    char a,b,c;

    cin>>a>>b>>c;

    if(isalpha(a) && isalpha(b) && isalpha(c) == 1)
    {
        cout<<"All of them are characters."<<endl;
    }
    else if(isalpha(a) == 1 && isalpha(b) ==1 && isalpha(c) == 0)
    {
        cout<<"The third input is not a valid alphabet.";
    }
    else if(isalpha(a) == 0 && isalpha(b) == 1 && isalpha(c) == 1)
    {
        cout<<"The first input is not a valid alphabet.";
    }
    else if(isalpha(a) == 1 && isalpha(b) == 0 && isalpha(c) == 1)
    {
        cout<<"The second input is not  valid alphabet.";
    }
    else if(isalpha(a) == 0 && isalpha(b) == 0 && isalpha(c) == 1)
    {
        cout<<"The first and second inputs are not valid alphabets.";
    }
    else if(isalpha(a) == 0 && isalpha(b) == 1 && isalpha(c) == 0)
    {
        cout<<"The first and third inputs are not valid alphabets.";
    }
    else if(isalpha(a) == 1 && isalpha(b) == 0 && isalpha(c) == 0)
    {
        cout<<"The second and third inputs are not valid alphabets.";
    }
    else if(isalpha(a) == 0 && isalpha(b) == 0 && isalpha(c) == 0)
    {
        cout<<"All of them are not valid alphabets.";
    }
    return 0;
}

不要忘記包含<cctype> header 文件。 在此處查看 output 文件。

暫無
暫無

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

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