Matthew McHugh
Matthew McHugh

Reputation: 5

How to convert string to double then print the output?

I'm new to C++ and just started learning earlier today. I'm trying to make a calculator that can take 2 inputs and print an output, just for some practice.

I can't figure out how to convert a string into a double, any suggestions on how to? (Please include sample code!)

This is what I have so far:

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

Upvotes: 0

Views: 882

Answers (2)

softwarenewbie7331
softwarenewbie7331

Reputation: 967

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

Edit: i was wrong, atof is for char array, use http://www.cplusplus.com/reference/string/stof/ instead

thanks @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);

Upvotes: 0

Shreevardhan
Shreevardhan

Reputation: 12651

Instead of declaring as string and converting to double, declare it as double

double numberOne;
double numberTwo;

Then, remove getline and input double directly

getline(cin, numberOne);

to

cin >> numberOne;

In case you wan't to stick to string, use std::stod to convert.

Upvotes: 3

Related Questions