在 C++ 中使用 switch 语句

Using the Switch Statement in C++

本文关键字:switch 语句 C++      更新时间:2023-10-16
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;
    }
}
}