修复未初始化的局部变量错误
Fixing uninitialized local variable error
我现在正在处理一个项目,当我尝试运行下面的内容时,它会给我一个错误,在第 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”);
- 为什么是错的?
祝您编码愉快!如果仍有问题,请告诉我
相关文章:
- 修复未初始化的局部变量错误
- 未初始化的局部变量错误甚至认为我初始化了它(C++)
- 我创建的类似乎错误地设置了它的局部变量
- 分配给静态变量的局部变量;编译错误在'c'但在 C++ 中成功
- 静态局部变量会被错误地优化吗?
- 错误 C4700:使用未初始化的局部变量'result'
- 尝试声明函数的局部变量,但得到范围错误
- 指针被分配给错误的局部变量
- 错误 C4700:使用未初始化的局部变量'enemyHealth'
- 在c++上创建税务计算程序,错误为未初始化的局部变量
- C++错误 C4700:使用未初始化的局部变量'i'
- 我不断收到错误:运行此代码时重新定义'i'。对局部变量的误解
- 从函数中引用局部变量不会给出错误
- 错误 C4700:使用未初始化的局部变量'A'
- C++:使用错误 C4700 未初始化的局部变量""
- 错误 C4700:使用未初始化的局部变量'lowest'
- 错误 1 错误 C4700:未初始化的局部变量'rate'并在C++中'hours'
- 全局变量如何在销毁时产生错误,而局部变量却不会
- 未初始化的局部变量使用错误
- 如何在循环外打印总和?我认为全局变量和局部变量的减速存在一些错误