簡體   English   中英

修復未初始化的局部變量錯誤

[英]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 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> 文件在這里
  • return不是函數調用,最好編寫return ch; return(ch);
  • if (ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X'){ return true; } else { return false; } if (ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X'){ return true; } else { return false; }完全等效於較短的return ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X'; return ch == 'I' || ch == 'O' || ch == 'L' || ch == 'X';
  • 還要看一下system(“pause”); -為什么錯了?

編碼愉快! 讓我知道是否還有問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM