我有这个代码。它应该完美。这是一个圆形计算器;我正在做的是锻炼。我希望用户可以选择返回“主菜单”。我使用char * 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 :(得分:2)
而不是:
char* e;
使用:
std::string e;
你得到的原因:
Unintialized local variable 'e' used
是传递给运营商&gt;&gt;时未设置e
cin使用它来初始化它为它分配一个数组,即:
char arr[128] = {0};
char* e = arr;
对于cin stream, operator>>
期望你提供了一些读取字符串所在的内存缓冲区,char* e;
没有绑定到任何这样的缓冲区,并且会以(可能)崩溃结束(未定义的行为) )。
答案 1 :(得分:1)
在这种情况下,您不需要。如果您只想从用户输入单个字母,请使用char
之类的
char response;
然后,您将它与字符文字进行比较,而不是像
那样的字符串文字if (response == 'N' || response == 'n')
如果你想与"no"
或"No"
这样的字符串进行比较,我建议你使用std::string
而不必担心必须为字符串分配内存。