我现在正在做一个项目,当我尝试运行下面的内容时,它给我一个错误,在第 22 行显示“使用了未初始化的局部变量‘userOption’”,而 (isValidOption(userOption) == true ) {. 我该如何修复该错误?谢谢。
#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
已经存在于<cctype>
.文档是 here -
return
不是函数调用,最好写成return ch;
比return(ch);
-
if (ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X'){ return true; } else { return false; }
完全等同于较短的return ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X';
- 另请查看
system(“pause”);
- Why is it wrong?
编码愉快!让我知道是否还有问题
关于c++ - 修复未初始化的局部变量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52918726/