2

首先,如果这是世界上最愚蠢的问题,让我道歉。但是,我被难住了,我在这里和谷歌上都做了很多搜索。我正在自学 C++,所以我可能不需要知道要搜索什么所需的词汇。

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

我有一个将字符串转换为双精度的函数:

    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;
}

我有一个函数可以在字符串中查找下一个数值:

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));
        }
    }
}

这是我用来将它们都称为测试的 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;
}

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

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

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

我将不胜感激您愿意提供的任何帮助。而且,由于这是我在这里的第一篇文章,我对任何风格指针都持开放态度。

4

1 回答 1

5

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

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

于 2012-06-28T12:18:33.680 回答