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

JLA*_*JLA 3 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Lin*_*vel 9

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

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