【问题标题】:Validating input and getline() function验证输入和 getline() 函数
【发布时间】:2015-12-30 22:05:29
【问题描述】:

所以我想验证用户只输入文本而不是数字。如果输入了任何数字,那么我再次要求她输入。我认为这可以解决问题,但它似乎不起作用:

#include <iostream>

using namespace std;

int main()
{
    string name = "";

    cout << "Enter name: ";
    getline(cin, name);

    while (!cin) // or cin.fail()
    {
        cout << "Numbers are not allowed, input name again: ";
        cin.clear();
        cin.ignore(1000, '\n'); // is this even necessary since getline() already consumes spaces and new lines?
        getline(cin, name);
    }
}

因为name 变量是string 类型,所以cin 对象在收到数字时不应该失败吗?如何验证它并确保在输入数字时再次提示输入?另外,出于好奇,因为我已经问过了,如果用户输入类似:Scarlett9356,那么重新提示输入的好方法是什么?谢谢。

【问题讨论】:

  • 您可以从输入流中将“1234”读取为数字或字符串:它只是一个字符串
  • 这里真正困难的是大局。什么是一个人的有效名字?它比人们想象的要复杂得多:kalzumeus.com/2010/06/17/… 当然,对于一个玩具程序,确保它只包含 Aa-Zz 和空格通常就足够了。
  • 精彩阅读,感谢分享! @ChristianHackl

标签: c++ validation io getline


【解决方案1】:

您可以通过这样做来验证您的字符串中没有数字:

#include <iostream>

using namespace std;

bool validName(string name)
{
    if(name.length() == 0)
        return false; // `name` cannot be empty

    for(int i = 0; i < name.length(); i++)
        if(name[i] >= '0' && name[i] <= '9') 
            return false; // There is a number in `name`

    return true; // `name` is valid
}

int main()
{
    string name = "";

    cout << "Enter name: ";
    getline(cin, name);

    while (!validName(name))
    {
        cout << "Numbers are not allowed, input name again: ";
        cin.clear();
        cin.ignore(1000, '\n'); // is this even necessary since getline() already consumes spaces and new lines?
        getline(cin, name);
    }
}

【讨论】:

  • 谢谢,我觉得它不错。但是,当我运行它时,按回车键一次将跳转到下一行,再次按回车键实际上会停止程序。我注释掉了cin.ignore() 行并修复了该问题的第一部分,但现在只需按 Enter 即可停止程序。可能是因为for 循环需要一些值来检查i &lt; name.length() 是否会造成混乱?
  • @Blueshift:我已经编辑了validName 函数来反映新的要求! ;-) 您可以为该函数添加更多条件!
【解决方案2】:

因为name变量是字符串类型,所以cin对象接收到数字不应该失败吗?

没有。由数字组成的输入也可以作为字符串有效。

您需要使用不同的策略来使该输入无效。

我会建议一些类似的东西:

bool is_valid_input(std::string const& name)
{
   bool is_valid = true;
   // Figure out the logic for deciding when the input is not valid.

   // ...

   if (!is_valid )
   {
      cout << "Numbers are not allowed, input name again: ";
   }

   return is_valid;
}

int main()
{
    string name = "";

    do
    {
       cout << "Enter name: ";
       getline(cin, name);
    }
    while ( !is_valid_input(name) );
}

【讨论】:

  • 知道了,谢谢。是否愿意发布一些示例代码或详细说明您的回复?
【解决方案3】:

如果您想将输入限制为只输入没有数字的字符串,那么您可以使用std::any_of 和std::isdigit

std::string name = "";

std::cout << "Enter name: ";
std::getline(std::cin, name);

while (std::any_of(name.begin(), name.end(), [](char ch) { return std::isdigit(ch); }))
{
    std::cout << "Numbers are not allowed, input name again: ";
    std::getline(std::cin, name);
}

【讨论】:

    猜你喜欢
    • 2012-10-28
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2014-12-21
    • 2021-01-14
    相关资源
    最近更新 更多