2016-02-08 40 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,而不必担心必须为字符串分配内存。