C ++菜单避免重复

时间:2013-01-29 21:47:36

标签: c++ file menu

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

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

以下代码是我的菜单选项:

int menuLoop = 1;
int userChoice;
std::string getInput;

while(menuLoop == 1)
{
    std::cout << "Menu\n\n" 
         << "1. 20 names\n"
         << "2. 100 names\n"
         << "3. 500 names\n"
         << "4. 1000 names\n"
         << "5. 10,000 names\n"
         << "6. 50,000 names\n\n";
    std::cin >> userChoice;

    std::string getContent;

    if(userChoice == 1)
    {
        std::cout << "\n20 names\n"; 
        std::ifstream openFile("20.txt");
    }
    else if(userChoice == 2)
    {
        std::cout << "\n100 names\n"; 
        std::ifstream openFile("1C.txt");
    }
    else if(userChoice == 3)
    {
        std::cout << "\n500 names\n"; 
        std::ifstream openFile("5C.txt");
    }
    else if(userChoice == 4)
    {
        std::cout << "\n1000 names\n"; 
        std::ifstream openFile("1K.txt");
    }
    else if(userChoice == 5)
    {
        std::cout << "\n10,000 names\n"; 
        std::ifstream openFile("10K.txt");
    }
    else if(userChoice == 6)
    {
        std::cout << "\n50,000 names\n"; 
        std::ifstream openFile("50K.txt");
    }

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

if(openFile.is_open())

由于我的方式,它说“openFile”是未定义的,我完全理解,但我想知道是否有人知道我怎么能绕过?

2 个答案:

答案 0 :(得分:2)

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

std::ifstream openFile;

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

openFile.open("20.txt");

当然,请确保每个人都有正确的文件名。

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

答案 1 :(得分:2)

也许是这样的:

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());