如何将字符串转换为double然后打印输出?

时间:2017-01-31 05:22:48

标签: c++

我是C ++的新手,刚刚开始学习。我正在尝试制作一个可以输入2个输入并打印输出的计算器,只是为了练习。

我无法弄清楚如何将字符串转换为double,有关如何的建议? (请附上示例代码!)

这是我到目前为止所做的:

#include <iostream>

using namespace std;

int main() {

string input = "";
string numberOne;
string numberTwo;
double output;

char myChar = {0};

while(true) {
    cout << "Add (A), Subtract (S), Multiply (M), Divide (D):\n> ";
    getline(cin, input);
    if (input.length() == 1) {
        myChar = input[0];
        if (input == "A") {
            cout << "Enter a number to add:\n> ";
            getline(cin, numberOne);
            cout << "Enter a number to add:\n> ";
            getline(cin, numberTwo);
            output = numberOne + numberTwo; //I know that I cannot do this because you can't 
                                           // add two strings and get a double, I just don't 
                                          // know how to make these two strings into doubles (or any other type). Any suggestions?
            cout << "The sum is: " + output << endl;
            output = numberOne + numberTwo
            break;
        }
        if (input == "S") {

        }
        if (input == "M") {

        }
        if (input == "D") {

        }
    }

    cout << "Invalid character, please try again" << endl;
}

return 0;
}

2 个答案:

答案 0 :(得分:3)

不是将其声明为字符串并转换为double,而是将其声明为double

double numberOne;
double numberTwo;

然后,删除getline并直接输入double

getline(cin, numberOne);

cin >> numberOne;

如果您不想坚持使用字符串,请使用std::stod进行转换。

答案 1 :(得分:0)

http://www.cplusplus.com/reference/cstdlib/atof/

            cout << "Enter a number to add:\n> ";
            getline(cin, numberOne);
            cout << "Enter a number to add:\n> ";
            getline(cin, numberTwo);
            output = atof(numberOne) + atof(numberTwo);

编辑:我错了,atof是char数组,使用http://www.cplusplus.com/reference/string/stof/ 而是

感谢@Shreevardhan

            #include <string>
            cout << "Enter a number to add:\n> ";
            getline(cin, numberOne);
            cout << "Enter a number to add:\n> ";
            getline(cin, numberTwo);
            output = stof(numberOne) + stof(numberTwo);