繁体   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