gpt4 book ai didi

c++ - switch 语句 C++ [默认部分]

转载 作者:行者123 更新时间:2023-11-30 03:55:55 25 4
gpt4 key购买 nike

我正在编写一个关于 switch 语句的基本程序。 5个选择的菜单,如果使用输入无效数字,应提示用户重新选择(范围为1-5)。这是我到目前为止得到的:

#include <iostream>
#include "Menu.h"
using namespace std;

void Menu::inputChoices()
{
int choice;

cout << "IHCC Computer Science Registration Menu" << endl;
cout << "1. Welome to Computer Programming in C++" << endl;
cout << "2. Welcome to Java Programming" << endl;
cout << "3. Welcome to Android Programming" << endl;
cout << "4. Welcome to iOS Programming" << endl;
cout << "5. Exit" << endl;
cout << "\nEnter your selection: " << endl;

while ((choice = cin.get()) != EOF)
{
switch (choice)
{
case '1':
cout << "Welcome to Computer Programming in C++" << endl;
break;
case '2':
cout << "Welcome to Java Programming" << endl;
break;
case '3':
cout << "Welcome to Android Programming" << endl;
break;
case '4':
cout << "Welcome to iOS Programming" << endl;
break;
case '5':
cout << "Exiting program" << endl;
break;
default:
cout << "Invalid input. Re-Enter your selection: " << endl;
}
}
}

这个项目有3个文件,这是源文件。我的问题是,当我输入的数字在 (1-5) 范围内时,开关的默认部分仍然会出现。我只想显示我的选择。谁能帮帮我!非常感谢

最佳答案

您还获得默认值的原因是因为 cin.get() 正在读取换行符 (10)。

我认为在这里使用 cin.get 没有意义,因为输入诸如 23987928asdasf 之类的内容会输出大量行。 .. 您应该使用 cin >> choice 并将您的案例转换为 int。像这样的东西:

cin >> choice;
switch (choice)
{
case 1:
cout << "Welcome to Computer Programming in C++" << endl;
break;
// ...
default:
cout << "Invalid input. Re-Enter your selection: " << endl;
}

关于c++ - switch 语句 C++ [默认部分],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28803011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com