2016-02-08 43 views
-2

我有這段代碼。它應該完美地工作。這是一個圈子計算器;我正在做的是一個練習。我希望用戶可以選擇返回「主菜單」。我用char * e做了一個yes/no的提示;但它未初始化。我怎麼能初始化使用未初始化的局部變量'e'

#include <iostream> 

using namespace std; 

class Circlecalc { 
public: 
    double const pi = 3.1415962543; 
    double diameter; 
    double radius; 
    double circumference; 

}; 

int _welcome() { 
    Circlecalc calc; 
    cout << endl; 
    int i = 0; 
    char* e; 
    cin >> i; 
    while (i != 5) 
    { 
     switch (i) { 
     case(1) : 
      cout << "Enter your radius." << endl; 
      cin >> calc.radius; 
      cout << endl; 
      cout << (calc.radius * 2) * calc.pi << endl; 
      cout << "Exit? [Y/N]" << endl; 
      cin >> e; 
      if (e == "Y") { 
       _welcome(); 
      } 

      else if (e == "N") { 
      } 

      else { 
       cerr << "Unsupported function" << endl; 
      } 

     case(2) : 
      cout << "Enter your diameter" << endl; 
      cin >> calc.diameter; 
      cout << endl; 
      cout << (calc.diameter * 2) * calc.pi << endl; 
      cout << "Exit? [Y/N]" << endl; 
      cin >> e; 
      if (e == "Y") { 
       _welcome(); 
      } 

      else if (e == "N") { 
      } 

      else { 
       cerr << "Unsupported function" << endl; 
      } 
      break; 

     case(3) : 
      cout << "Enter the circumference" << endl; 
      cin >> calc.circumference; 
      cout << endl; 
      cout << (calc.circumference/2)/calc.pi; 
      cout << "Exit? [Y/N]" << endl; 
      cin >> e; 
      if (e == "Y") { 
       _welcome(); 
      } 

      else if (e == "N") { 
      } 

      else { 
       cerr << "Unsupported function" << endl; 
      } 
      break; 

     case(4) : 
      cout << "Enter the circumference" << endl; 
      cin >> calc.circumference; 
      cout << endl; 
      cout << calc.circumference/calc.pi; 
      cout << "Exit? [Y/N]" << endl; 
      cin >> e; 
      if (e == "Y") { 
       _welcome(); 
      } 

      else if (e == "N") { 
      } 

      else { 
       cerr << "Unsupported function" << endl; 
      } 
      break; 

     case(5) : 
      return(0); 
      break; 

     default: 
      cerr << "Unsupported function." << endl; 
     } 
    } 
} 
+0

用'std :: string e;'替換'char * e;' – Jarod42

+0

編譯器在哪一行中抱怨? –

+0

它是什麼意思? –

回答

2

相反的:

char* e; 

使用:

std::string e; 

的原因,你可以:

Unintialized local variable 'e' used 

是過去了e未設置運營商>>這就是我們通過CIN編,以初始化它分配一個數組給它,即:

char arr[128] = {0}; 
char* e = arr; 

operator>>爲CIN流想到你已經提供了一些存儲器緩衝器,其中讀出的字符串的位置,char* e;不綁定到任何這樣的緩衝器,和那會以(可能)崩潰(未定義的行爲)結束。

1

在這種情況下,你不需要。如果你只是想從用戶的單個字母輸入只使用一個char

char response; 

那麼你會比較它針對文字而不是字符串文字像

if (response == 'N' || response == 'n') 

字符如果你想比較針對像"no""No"這樣的字符串,那麼我建議您使用std::string,而不必擔心必須爲字符串分配內存。