2017-01-31 2 views
0

私は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; 
} 
+0

以下のShreevardhanの提案を使用するべきでしょうが、 'string'を' double'に変換する必要がある場合、C++ 11は 'std :: stod'関数を提供します。 'std :: stringstream'は別のオプションです。 –

答えて

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

代わりに、文字列として宣言し、倍増次にダブル

double numberOne; 
double numberTwo; 

として宣言し、場合getlineの入力ダブル直接

getline(cin, numberOne); 

cin >> numberOne; 

を除去するために変換する

+0

私はそれを入力するとどうなりますか?エラー: 'std :: string {aka std :: basic_string }'を 'const char *'に '1'から 'double atof(const char *)'に変換できません。 –

+0

@MatthewMcHugh ['std :: stod'](http://en.cppreference.com/w/cpp/string/basic_string/stof) – Shreevardhan

+0

私の間違いは、編集された回答を参照してください。 – softwarenewbie7331

関連する問題