在 C++ 中使用 switch 语句
Using the Switch Statement in C++
case'1':
{
... // case 1 will require you to input a ID number and a bunch of info..
break;
}
case'2':
{
...// case 2 is gonna search the ID and display the info
break;
}
结果会像..
Whats your choice :1
Enter a ID no. : 0001 //USER is ask to make a ID number
Enter Name : Paolo //USER is ask to enter a Name
Enter Address: blah blah //USER is ask to enter an address
。然后,如果所有输入都已填充,它将返回菜单。
whats your choice :2
Enter ID : 0001 //User is ask to enter the ID number he created
Name : paolo // DISPLAY THE NAME
address : blah blah //DISPLAY THE ADDRESS
编辑:修改了我的问题,开关语句可以做到吗。?
在 C 语言中,你需要一个Person
结构数组。 例如:
typedef struct
{
char name[MAX_NAME];
char address[MAX_ADDRESS];
} person;
person people[MAX_PEOPLE];
然而,我不是C++专家,所以可能有更好的方法。
正如我从"如何在不替换第一个的情况下进行多个 ID 和信息输入"中理解的那样。 您应该将与每个ID关联的信息存储在特殊数组中(例如,标准::地图)。
#include <map>
#include <string>
#include <iostream>
using namespace std;
struct IdInfo {
string name;
string address;
};
int main() {
std::map<std::string, IdInfo> idsInfo;
while (true) {
cout << "ninput 1 or 2:";
char input = (int)getchar();
cin.get();
switch (input) {
case '1': {
cout << "nwrite id:";
std::string id;
getline(cin, id);
cout << "nwrite name:";
std::string name;
getline(cin, name);
cout << "nwrite address:";
std::string address;
getline(cin, address);
IdInfo newInfo;
newInfo.name = name;
newInfo.address = address;
idsInfo[id] = newInfo;
break;}
case '2': {
std::string id2;
cout << "nwrite id:";
getline(cin, id2);
IdInfo info = idsInfo[id2];
std::cout << "ninfo:" << info.name << " " << info.address;
break;}
default:
// Finish execution.
return 0;
break;
}
}
}
相关文章:
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 如何将 if else 语句重写为 switch 语句
- Switch 语句(字符串)一直选择默认值,除非其为零
- C++ switch 语句:对案例进行分组,并针对每个案例给出特定的说明
- 任意大小的 constexpr 数组是否可以用作 switch 语句中的案例?
- 默认标签显然在 switch 语句中不起作用
- C++如何在 switch 语句中放置两个参数
- 如何在 c++ 中从 switch 语句返回不同类型的变量
- 在编译时自动生成用于稀疏数组索引的switch语句
- C++ Switch 语句中的数学运算
- 变量不能在 lambda 中隐式捕获,并且没有使用 switch 语句指定捕获默认值
- 在任何案例之前,在 switch 语句中的使用声明是否合法?
- 使用 switch 语句将不同的函数作为类属性分配 C++
- 为什么我的 switch 语句没有响应一半的情况?
- 如何从映射中获取值并在 C++ 的 switch 语句中使用它
- switch 语句导致发送两条消息
- C++ Switch 语句在中断后执行
- switch语句,两种类似情况不同
- switch 语句和对象隐式 int 转换
- switch 语句结束和下一条语句之间的时间是否具有确定性(与路径无关)