在条件下尝试将字符串转换为双精度

Roa*_*ash 0 c++ atof

我有一个使用std字符串参数来测试是否有字母字符的函数。最好只测试数字字符,但到目前为止我还没有得到。我只是想让它识别输入中是否没有数字。如果不是,它将循环显示错误消息,直到只有数字为止。在此之后,我尝试使用atof()将字符串转换为double,以便可以在main()中返回它。我得到调试断言失败!运行时的消息,其中说,如果输入数字,则表达式字符串下标超出范围。否则,如果输入了字母,它将继续使用错误消息循环其自身。我得到了下面函数的代码。有人对我做错了什么有任何线索吗?我没主意...

double Bet::betProb(std::string b)
{
    bool alphChar = false;
    double doubleBet;
    for(int i = 0; i < b.size(); i++){
        if(isalpha(b[i])){
            alphChar = true;
        }
    }
    while(alphChar){
        cout << "Error! Bet only with numbers." << endl;
        cin >> b;
        for(int i = 0; i < b.size(); i++){

            if(!isalpha(b[i])){
                alphChar = false;
            }
        }
    }

    string F=b;
    int T=F.size();
    char Change[100];
    for (int a=0;a<=T;a++)
    {
        Change[a]=F[a];
    }

    doubleBet = atof(Change);

    return doubleBet;
}
Run Code Online (Sandbox Code Playgroud)

0x4*_*2D2 5

由于您的问题已经解决,因此我想向您展示使用标准C ++功能实现此方法的方法:

#include <string>
#include <stdexcept>

double Bet::betProb(const std::string& str)
{
    double d;

    try {
        d = std::stod(str);
    } catch (const std::invalid_argument&) {
        std::cerr << "Argument is invalid\n";
        throw;
    } catch (const std::out_of_range&) {
        std::cerr << "Argument is out of range for a double\n";
        throw;
    }
    return d;
}
Run Code Online (Sandbox Code Playgroud)