如何验证字符串中只有数字?

时间:2013-10-30 09:35:28

标签: c++

我是C ++的新手。我正在开发一个项目,我需要通过控制台从用户那里读取大部分整数。为了避免某人输入非数字字符,我考虑将输入作为字符串读取,检查其中只有数字,然后将其转换为整数。我创建了一个函数,因为我需要多次检查整数:

bool isanInt(int *y){
    string z;
    int x;
    getline(cin,z);
    for (int n=0; n < z.length(); n++) {
        if(!((z[n] >= '0' && z[n] <= '9') || z[n] == ' ') ){
            cout << "That is not a valid input!" << endl;
            return false;
        }
    }
    istringstream convert(z); //converting the string to integer
    convert >> x;
    *y = x;
    return true;
}

当我需要用户输入一个整数时,我会调用这个函数。但由于某些原因,当我调用此函数时,程序不会等待输入,它会立即跳转到for循环处理空字符串。有什么想法吗?谢谢你的帮助。

6 个答案:

答案 0 :(得分:9)

有许多方法可以仅为数字字符测试字符串。一个是

bool is_digits(const std::string &str) {
    return str.find_first_not_of("0123456789") == std::string::npos;
}

答案 1 :(得分:3)

这样可行:

#include <algorithm> // for std::all_of
#include <cctype>    // for std::isdigit

bool all_digits(const std::string& s)
{
  return std::all_of(s.begin(), 
                     s.end(), 
                     [](char c) { return std::isdigit(c); });
}

答案 2 :(得分:2)

你可以在try / catch块中强制转换字符串,这样如果转换失败,你就会引发异常,你可以在控制台中写下你想要的任何内容。

例如:

  try
  {
    int myNum = strtoint(myString);
  }
  catch (std::bad_cast& bc)
  {
     std::cerr << "Please insert only numbers "<< '\n';
  }

答案 3 :(得分:2)

字符分类是通常委派给区域设置的ctype方面的工作。您将需要一个考虑所有9位数的函数,包括千位分隔符和小数点:

bool is_numeric_string(const std::string& str, std::locale loc = std::locale())
{
    using ctype = std::ctype<char>;
    using numpunct = std::numpunct<char>;
    using traits_type =  std::string::traits_type;

    auto& ct_f  = std::use_facet<ctype>(loc);
    auto& np_f = std::use_facet<numpunct>(loc);

    return std::all_of(str.begin(), str.end(), [&str, &ct_f, &np_f] (char c)
    {
        return ct_f.is(std::ctype_base::digit, c) || traits_type::eq(c, np_f.thousands_sep())
                                                 || traits_type::eq(c, np_f.decimal_point());
    });
}

请注意,额外的工作可以确保千位分隔符不是第一个字符。

答案 4 :(得分:-1)

尝试另一种方式,如cin.getline(str,sizeof(str)),str这里是char *。我认为在调用此函数之前,问题可能是由其他函数引起的。也许你可以仔细检查你的代码的其他部分。也建议使用断点设置。

答案 5 :(得分:-2)

始终使用现成的功能。永远不要一个人写 我建议 std::regex

享受。