返回不适用于float或int,但是可以使用字符串吗?

tob*_*den 2 c++ string floating-point return function

首先,如果这是世界上最愚蠢的问题,请向我道歉.但是,我很难过,我在这里和谷歌都做了很多搜索.我正在自学C++,所以我可能没有必要的词汇来知道要搜索什么.

我正在尝试编写一个有限状态机来解析方程式.我知道以前做过,但我正在努力学习.为此,我希望能够获取一个字符串,识别数字,并将它们转换为双打或浮点数.(我会接受你对使用哪种格式的建议.)

我有一个函数将字符串转换为double:

    double convertToDouble(string value)
{
    /* -- From http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2
        Using stringstream, convert a string to a double by treating it like a stream
    */
    istringstream stream(value);
    double doubleValue;
    stream >> doubleValue;
    return doubleValue;
}
Run Code Online (Sandbox Code Playgroud)

我有一个函数来查找字符串中的下一个数值:

string evaluateNextValue (int operatorPosition, string equation)
{
    /* -- Find the next value
        My idea is that, since I'm using spaces as my dividers, we'll look for
        the first number and then, using insert to put the individual numbers
        into a string until a space is found again. Then, the numbers--now
        in the correct order--can be converted to a double and returned
    */
    bool digitFound = false;
    string workingNumbers;
    for (int pos = operatorPosition; pos < equation.size(); pos ++)
    {
        if (equation.at(pos) == ' ' && digitFound == true)
        {
            double result = convertToDouble(workingNumbers);
            cout << "Converting a string to " << result << endl;
            cout << "The result plus one is: " << result +1 << endl;
            return workingNumbers;
        } else if (equation.at(pos) == ' ' && digitFound == false)
        {
            cout << "Skipping a blank space." << endl;
            continue;
        } else
        {
            if (digitFound == false)
            {
                digitFound = true;
                cout << "First digit found." << endl;
            }
            cout << "Adding " << equation.at(pos) << " to the string." << endl;
            workingNumbers.insert(workingNumbers.end(),equation.at(pos));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是main()我用来称它们作为一种测试.

int main()
{
    string dataInput;
    cout << "Insert a number" << endl;
    getline(cin, dataInput);
    cout << "You entered: " << dataInput << endl;
    double numberValue = convertToDouble(evaluateNextValue(0, dataInput));

    cout << "Adding ten: " << numberValue + 10;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

事情是这样的:就像现在一样,evaluateNextValue()返回一个字符串,它可以工作.这对我来说似乎有点笨拙(可能这一切对你来说都是笨拙的),但它确实有效.

当我让代码操作函数中的变量结果时,它工作正常.我只是将字符串转换为double,我可以使用它.

但是,当我将字符串转换为double并尝试返回double时...double在函数本身中工作正常.但是当它到达main()时它就是nan.甚至更奇怪(或者同样奇怪,无论如何)是试图返回一个int DOES返回一个int,但从来没有任何远程连接到我输入的值.

我很感激您提供的任何帮助.而且,由于这是我在这里的第一篇文章,我对任何风格指针持开放态度.

thi*_*ton 5

如果evaluateNextValue由于for循环条件而到达字符串的末尾,则返回值是未定义的(因为return那里没有语句).这会触发未定义的行为,包括返回NaN值.

您应该启用编译器的警告来捕获此类错误.