C++菜单避免重复

C++ menu avoid repetition

本文关键字:菜单 C++      更新时间:2023-10-16

感谢您提前查看我的问题。这可能很简单!

我有一个菜单,用户可以在其中选择他们希望通过系统运行的文件。

下面的代码是我的菜单选项的作用:

int menuLoop = 1;
int userChoice;
std::string getInput;
while(menuLoop == 1)
{
    std::cout << "Menunn" 
         << "1. 20 namesn"
         << "2. 100 namesn"
         << "3. 500 namesn"
         << "4. 1000 namesn"
         << "5. 10,000 namesn"
         << "6. 50,000 namesnn";
    std::cin >> userChoice;
    std::string getContent;
    if(userChoice == 1)
    {
        std::cout << "n20 namesn"; 
        std::ifstream openFile("20.txt");
    }
    else if(userChoice == 2)
    {
        std::cout << "n100 namesn"; 
        std::ifstream openFile("1C.txt");
    }
    else if(userChoice == 3)
    {
        std::cout << "n500 namesn"; 
        std::ifstream openFile("5C.txt");
    }
    else if(userChoice == 4)
    {
        std::cout << "n1000 namesn"; 
        std::ifstream openFile("1K.txt");
    }
    else if(userChoice == 5)
    {
        std::cout << "n10,000 namesn"; 
        std::ifstream openFile("10K.txt");
    }
    else if(userChoice == 6)
    {
        std::cout << "n50,000 namesn"; 
        std::ifstream openFile("50K.txt");
    }

while 循环中的代码处理所选文件中的值,但每个选项的代码相同。下一行是:

if(openFile.is_open())

由于我这样做的方式,它说"openFile"是未定义的,我完全理解,但我想知道是否有人知道我该如何绕过?

while循环中提前声明一次openFile,如下所示:

std::ifstream openFile;

这为您提供了一个不与任何特定文件关联的std::ifstream。然后在每个if语句中使用 std::ifstream::open 而不是 std::ifstream 构造函数:

openFile.open("20.txt");

当然,请确保每个文件名正确。

这样,openFile对象的作用域将是while循环,但您可以根据条件打开不同的文件。

也许是这样的:

const MAX_OPTION = 6;
std::array< std::string, MAX_OPTION > filenames = {"20.txt","1C.txt","5C.txt","1K.txt","10K.txt","50k.txt"};
//your while loop
//...
cin >> userChoice;
//assert userChoice >= 0 < filenames.size
const std::string& filename = filenames[ userChoice ];
std::ifstream openFile(filename.c_str());