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

标签 c++ visual-studio

我现在正在做一个项目,当我尝试运行下面的内容时,它给我一个错误,在第 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/

相关文章:

c++ - 如何修复 "invalid type argument of ' 一元'?

c++ - 如果指针的大小都相同,为什么我们必须声明它们指向的对象类型?

visual-studio - Visual Studio 2015 中缺少添加 Controller 选项

c# - 反序列化似乎不适用于 IDE 中的强命名对象

c# - 资源文件 (resx) 不遵守自定义工具命名空间

c++ - Doxygen STL 支持使用点图

c++ - 在 QML 中使 QList<QObject*> C++ 模型动态化

c++ - 使用 openmp 优化循环

c# - 如果使用 C# 表达式(或抛出错误),则在 Visual Studio 中警告开发人员

visual-studio - 在 Visual Studio 调试器中查看非平凡表达式时出现问题