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

时间:2018-10-21 18:50:47

标签: 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;
}

1 个答案:

答案 0 :(得分:1)

该错误表示您正在尝试从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?

祝您编程愉快!让我知道是否还有问题