修复未初始化的局部变量错误

Fixing uninitialized local variable error

本文关键字:局部变量 错误 初始化      更新时间:2023-10-16

我现在正在处理一个项目,当我尝试运行下面的内容时,它会给我一个错误,在第 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 optionsn";
cout << "I--List Our Inventoryn";
cout << "O--Make an Ordern";
cout << "L--List all Orders maden";
cout << "X--Exitn";
cout << "Enter an option: ";
getline(cin, UserInput);
userOption = toupper(UserInput[0]);
if (!isValidOption(userOption)) {
cout << "Invalid Stringn";
cout << "Enter an option: ";
getline(cin, UserInput);
userOption = toupper(UserInput[0]);
}
if (userOption == 'I')
cout << "Listing Our Inventoryn";
else if (userOption == 'O')
cout << "Make an ordern";
else if (userOption == 'L')
cout << "Listing all ordersn";
}
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>.文档在这里
  • 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”);- 为什么是错的?

祝您编码愉快!如果仍有问题,请告诉我