簡體   English   中英

如何僅在C ++中將用戶輸入限制為數字和字母

[英]How to limit input from user to numbers and letters only in C++

該程序僅需要數字和/或字母作為用戶輸入。 否則,該程序必須終止。 我不知道如何將輸入限制為僅數字和字母。

這是我的程序:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string input, reversed = "";

    cout << "Enter string: "; 
    cin >> input;

    for (int i = input.length() - 1; i < input.length(); i--)
    {
        reversed += input[i];
    }
    cout << reversed << endl;

    if (reversed == input)  cout << "It is a palindrome!"; 
    else            cout << "No, it is not a palindrome!";
    return 0;
}

實現所需內容的最簡單方法是檢查每個字符。 正如@Pete Becker指出的那樣,您可以使用isalnum來檢查字符是數字還是字母字符:

#include <iostream>
#include <string>

int main () {
  std::string s = "Hello W>orld";

  for (auto c : s) {
    if (!isalnum(c)) {
      std::cout << "Found : '" << c << "'" << std::endl;
    }
  }

  return 0;
}

輸出:

Found : ' '
Found : '>'

正如@Someprogrammerdude在評論中提到的那樣,使用std :: all_of和適當的二進制謂詞(lambda函數),您可以輕松地做到以下幾點。

其次,要檢查input到其反向字符串的字符串,只需使用std::string 的反向迭代器創建一個臨時std::string並進行檢查。 這樣,您就不需要另一個變量。

希望這些評論將幫助您了解更多選項。 現場直播

#include <iostream>
#include <cctype> // std::isdigit and std::isalpha and std::isalnum
#include <string>
#include <algorithm> // std::all_of

int main()
{
    std::string input; std::cin >> input;

    const auto check = [](const char eachCar)->bool{ return std::isalnum(eachCar); };
    /* change return statement of lambda to
        std::isdigit(eachCar)  ---> for only digits
        std::isalpha(eachCar)  ---> for only letters
    */
    if(std::all_of(input.cbegin(), input.cend(), check))
    {
        if(input == std::string(input.crbegin(), input.crend()))
            std::cout << "It is a palindrome!";
        else  std::cout << "No, it is not a palindrome!";
    }
    return 0;
}

輸入

123kk321

輸出

It is a palindrome!

假設輸入沒有空間,可以這樣:

char c; string s; bool chk = true;
while (cin >> c) 
{
    if (('0' <= c && c <= '9') || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')) 
        s.push_back(c);
    else chk = false;
}
if (chk == true) cout << "Valid string";
else cout << "Invalid string";

當輸入中沒有字符時,以上代碼將終止。

暫無
暫無

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

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