1

感谢您提前查看我的问题。这可能是一个很简单的事情!

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

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

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”是未定义的,我完全理解,但我想知道是否有人知道我该如何解决?

4

2 回答 2

2

像这样在循环的前面声明openFile一次:while

std::ifstream openFile;

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

openFile.open("20.txt");

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

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

于 2013-01-29T21:49:23.007 回答
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());
于 2013-01-29T22:12:12.627 回答