简体   繁体   中英

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

The program only needs numbers and/or letters as input from the user. otherwise, the program must be terminated. I don't know how to limit the input to numbers and letters only.

Here is my program:

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

The simplest way you can achieve what you want is checking every character. As @Pete Becker pointed out, you may use isalnum to check if the character is a number or a letter character:

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

Output:

Found : ' '
Found : '>'

As @Someprogrammerdude mentioned in the comments, using std::all_of and an appropriate binary predicate(lambda function), you can do it easily as follows.

Secondly, for checking the string input to its reverse string, just create a temporary string using the reverse iterators of std::string and check it. That way, you do not need to have another variable.

Hope the comments will help you to understand more options. SEE LIVE

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

Input :

123kk321

Output :

It is a palindrome!

Assume the input has no space, you can do like this:

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

The above code will terminate when there is no character left in the input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM