0

嘿,当我要求用户输入名称时,我想阻止用户输入整数。我已经为整数和字符实现了这一点。谁能帮我调整我的代码以适应字符串。

int getNum()
{
    int num;
    std::cout << "\nWhat is your age? ";
    while (!(std::cin >> num))
    {
        // reset the status of the stream
        std::cin.clear();
        // ignore remaining characters in the stream
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Enter an *integer*: ";
    }
    std::cout << "You entered: " << num << std::endl;
    return num;
}

char getChar(string q)
{
    char input;
    do
    {
        cout << q.c_str() << endl;
        cin >> input;
    }
    while(!isalpha(input));
    return input;
}
4

2 回答 2

1

如果您打算使用 std:string,那么您可以使用它来查找输入的字符串是否有任何数字:

if (std::string::npos != s.find_first_of("0123456789"))
{
  std::cout << "digit(s)found!" << std::endl;
}
于 2012-10-18T14:26:01.563 回答
1
string q = "This is a test123";

for(string::iterator i = q.begin(); i != q.end(); i++)
{
    if((*i < 'A' || *i > 'z') && (*i != ' '))
    {
        return false;
    }
}

如果您允许空格和其他字符,这也是一种选择。

编辑:更新以检查单个字符:

char c;
bool finished = false;
printf("Please enter your sex, M/F?\n");
while(!finished)
{
    cin >> c;
    if(!(c == 'm' || c == 'M' || c== 'f' || c=='F'))
    {
        printf("Please try again...\n");
    }
    else
    {
        finished = true;
    }
}

请注意,当按下 Enter 时,c 只是逐个字符地输入,在此之前不会发生换行。

于 2012-10-18T14:34:51.917 回答