C++ 正在修复未初始化的局部变量错误
我现在正在处理一个项目,当我尝试运行下面的内容时,会出现一个错误,即第22行使用了未初始化的局部变量“userOption”,而isValidOptionuserOption==true{。 我该如何修复该错误?谢谢C++ 正在修复未初始化的局部变量错误,c++,visual-studio,C++,Visual Studio,我现在正在处理一个项目,当我尝试运行下面的内容时,会出现一个错误,即第22行使用了未初始化的局部变量“userOption”,而isValidOptionuserOption==true{。 我该如何修复该错误?谢谢 #include<iostream> #include <string> using namespace std; char toupper(char ch) { if (ch >= 'A'&&ch <= 'Z')
#include<iostream>
#include <string>
using namespace std;
char toupper(char ch) {
if (ch >= 'A'&&ch <= 'Z')
return(ch);
else
return(ch - 32);
}
bool isValidOption(char ch) {
if (ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X')
return(true);
else
return(false);
}
char getMainOption() {
string UserInput;
char userOption;
while (isValidOption(userOption) == true) {
cout << "Choose One of the following options\n";
cout << "I--List Our Inventory\n";
cout << "O--Make an Order\n";
cout << "L--List all Orders made\n";
cout << "X--Exit\n";
cout << "Enter an option: ";
getline(cin, UserInput);
userOption = toupper(UserInput[0]);
if (!isValidOption(userOption)) {
cout << "Invalid String\n";
cout << "Enter an option: ";
getline(cin, UserInput);
userOption = toupper(UserInput[0]);
}
if (userOption == 'I')
cout << "Listing Our Inventory\n";
else if (userOption == 'O')
cout << "Make an order\n";
else if (userOption == 'L')
cout << "Listing all orders\n";
}
return userOption;
}
int main() {
char choice;
choice = getMainOption();
system("pause");
return 0;
}
错误的意思是,您试图在写入userOption之前读取它。如果变量未初始化,它的内存内容将充满其他函数留下的垃圾,并且很容易导致错误。在您的情况下,您希望在对其执行任何逻辑之前将用户输入读取到userOption。这可能会导致错误使用do while循环完成:
char userOption; // not yet initialized
do {
...
cin >> userOption; // userOption gets initialized here on first loop run
} while (isValidOption(userOption)); // no need for == true, that's a tautology :-)
// NOTE: perhaps you want to loop while the input is INvalid, as in
// while (!isValidOption(userOption)); ?
另外,我还想给出一些代码审查意见:
std::toupper已存在于中。文档为
return不是函数调用,最好编写return ch;而不是returnch;
如果ch='I'| ch='O'| ch='L'| ch='X'{return true;}否则{return false;}完全等同于较短的返回值ch='I'| ch='O'| ch='L'| ch='X';
也来看看
愉快的编码!如果问题仍然存在,请告诉我:char userOption='';使用将通过isValidOption测试的值,或者可能使用Do while循环。您应该重新考虑您的while循环:在获得用户输入后,应检查条件isValidOptionuserOption==true。并且,可能应该是isValidOption userOption!是的。