c ++ toDouble()将字符串转换为0

时间:2016-02-13 03:15:52

标签: c++ qt

所以我的想法是,对于按下的每个数字,数字被推到nums双端队列。然后,当按下小数点按钮时,它会将所有nums推送到名为specialDecimal的新双端队列并按下#34;"在这些数字之后。还将名为decimalClicked的布尔值设置为true。所以现在我有小数前的数字+小数。然后,当按下操作符时,它会将nums中的数字(小数点后的数字)推送到specialDecimal。那么当按下等于按钮时,我会对decimalClicked进行特殊评估:

//special case if decimal is pressed
double actualVal = 0;
QString s = "";
bool ok; //for toDouble

if(decimalClicked){
    while(!(specialDecimal.empty())){
        QString s = specialDecimal.front();
        cerr << s.toStdString();
        s.append(s);
        specialDecimal.pop_front();
    }
    cerr << endl << "should be whole string number: " << s.toStdString();
    actualVal = s.toDouble(&ok);
    cerr << endl << "should be value: " << actualVal;
    nums.push_front(actualVal);
}`

cerr的输出是:

8.1
should be whole string number: 
should be value: 0

while循环中的cerr print语句表明它正在正确解析十进制数。 while循环下的cerr语句不会打印出整个字符串。如果我执行运算符the second number,显示的结果基本上是0 + +。如果需要,我可以显示更多代码。

1 个答案:

答案 0 :(得分:1)

错误是可变范围之一。

//special case if decimal is pressed
double actualVal = 0;
QString s = ""; // <----------------------- s variable declared in outer scope
bool ok; //for toDouble

if(decimalClicked){
    while(!(specialDecimal.empty())){
        QString s = specialDecimal.front(); // <-- s variable declared in
                                            //     while loop scope which
                                            //     hides the s variable
                                            //     in the outer scope
        cerr << s.toStdString();
        s.append(s);
        specialDecimal.pop_front();
    } // <---------------------------------- second s variable goes out 
      //                                     of scope         
    cerr << endl << "should be whole string number: " << s.toStdString();
    actualVal = s.toDouble(&ok);
    nums.push_front(actualVal);
}

请改为尝试:

//special case if decimal is pressed
double actualVal = 0;
QString s = "";
bool ok; //for toDouble

if(decimalClicked){
    while(!(specialDecimal.empty())){
        QString a = specialDecimal.front();  // note variable renamed to avoid
                                             // collision
        cerr << s.toStdString();
        s.append(a);
        specialDecimal.pop_front();
    }
    cerr << endl << "should be whole string number: " << s.toStdString();
    actualVal = s.toDouble(&ok);
    nums.push_front(actualVal);
}