C++菜单避免重复
C++ menu avoid repetition
感谢您提前查看我的问题。这可能很简单!
我有一个菜单,用户可以在其中选择他们希望通过系统运行的文件。
下面的代码是我的菜单选项的作用:
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());
相关文章:
- 无法获取菜单选择以运行函数.C++
- C++ 中的图形菜单
- C++ 程序菜单使用做同时和切换
- 我正在尝试创建一个菜单,但我的代码一直在循环
- 触发另一个窗口的菜单按钮
- 从子菜单返回后,正确的输入至少进入验证循环一次
- C++ 我的开关格式中的循环不允许我显示菜单选项或接受输入?
- 如何为我的游戏设置主菜单场景?QT C++
- C++循环菜单时做
- 难以从 CImageList 设置菜单项位图
- 如何将我的程序添加到文件和文件夹的macOS右键单击菜单?
- 如何以编程方式显示功能区按钮的下拉菜单?
- 如何在win32的窗口类中设置动态菜单?
- 为什么我的 Do-while 循环无法在C++中运行菜单
- 我正在尝试用 c++ 制作菜单,但不明白为什么它不循环
- 如何使用IExecuteCommand和动词在上下文菜单外壳扩展中显示本地化文本和自定义图标?
- 连接资源文件中的字符串,并将其传递给菜单项字符串 (winapi) c++
- 需要帮助主菜单C++
- 获取 c++ mfc vs2015 中弹出资源菜单项的 id
- QT 窗口模式禁用菜单中的操作