Using the Switch Statement in C++
1 2 3 4 5 6 7 8 9 10 11 | 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; } |
结果是……
1 2 3 4 5 | 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 |
…然后,如果所有输入都被填满,它将返回到菜单。
1 2 3 4 | 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 |
编辑:修改了我的问题,switch语句能做到吗?
在C中,您需要一个
1 2 3 4 5 6 7 | typedef struct { char name[MAX_NAME]; char address[MAX_ADDRESS]; } person; person people[MAX_PEOPLE]; |
但是我不是C++专家,所以也许有更好的方法。
正如我从"如何在不替换第一个ID和信息的情况下输入多个ID和信息"中所理解的。您应该将与每个ID相关联的信息存储在特殊的数组中(例如std::map)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | #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 <<" input 1 or 2:"; char input = (int)getchar(); cin.get(); switch (input) { case '1': { cout <<" write id:"; std::string id; getline(cin, id); cout <<" write name:"; std::string name; getline(cin, name); cout <<" write 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 <<" write id:"; getline(cin, id2); IdInfo info = idsInfo[id2]; std::cout <<" info:" << info.name <<"" << info.address; break;} default: // Finish execution. return 0; break; } } } |