簡體   English   中英

Return對float或int不起作用,但是對string有效嗎?

[英]Return doesn't work with float or int, but does work with string?

首先,讓我道歉,如果這是世界上最愚蠢的問題。 但是,我很困惑,在這里和Google上都做了很多搜索。 我正在自學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()返回一個字符串,它可以工作。 對我來說似乎有點笨拙(也許對您來說一切似乎都很笨拙),但它確實有效。

當我讓代碼操縱函數中的變量結果時,它可以正常工作。 我只是將字符串轉換為雙精度字,我就可以使用它。

但是 ,當我將字符串轉換為雙精度型並嘗試返回雙精度型時。 雙重功能本身很好。 但是當它到達main()時是難事。 甚至更奇怪(或無論如何也很奇怪)的事實是,嘗試返回一個int確實會返回一個int,但絕不會有任何遠程連接到我輸入的值。

感謝您提供的任何幫助。 並且,因為這是我在這里的第一篇文章,所以我對任何樣式指針都開放。

如果由於for循環的條件, evaluateNextValue到達字符串的末尾,則返回值是不確定的(因為那里沒有return語句)。 這將觸發未定義的行為,其中可能包括返回的NaN值。

您應該啟用編譯器的警告以捕獲此類錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM