【问题标题】:Validate console input in c++在 C++ 中验证控制台输入
【发布时间】:2016-06-05 17:04:58
【问题描述】:

我写了下面的代码,它在有效输入的情况下工作

char input[100];
cin.getline(input, sizeof(input));
stringstream stream(input);
while (stream.rdbuf()->in_avail() != 0) {
    int n;
    stream >> n;
    numbers.push_back(n);
}

但是当我输入一些东西而不是数字时失败。 如何处理错误的输入(例如任何字母)?

【问题讨论】:

标签: c++


【解决方案1】:

例如:

bool is_number(const std::string& s)
{
    return !s.empty() && std::find_if(s.begin(), 
        s.end(), [](char c) { return !std::isdigit(c); }) == s.end();
}

foo() {
    char input[100];
    cin.getline(input, sizeof(input));
    stringstream stream(input);
    while (stream.rdbuf()->in_avail() != 0) {
        std::string n;
        stream >> n;
        if(is_number(n)) {
            numbers.push_back(std::stoi(n));
        }
        else {
            std::cout << "Not valid input. Provide number" << std::endl;
        }
    }
}

int main()
{
    foo();
    return 0;
}

【讨论】:

  • 谢谢。你忘了#include
  • @djaszak 不客气。是的,我没有写任何包含。
猜你喜欢
  • 1970-01-01
  • 2014-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 1970-01-01
相关资源
最近更新 更多