gpt4 book ai didi

C++我如何做一个添加新值并可以删除现有值的循环

转载 作者:行者123 更新时间:2023-11-28 07:59:00 31 4
gpt4 key购买 nike

感谢阅读这个问题。

基本上我正在尝试做一个可以实现以下目标的代码:

用户将看到这样的详细信息列表

终端 View :

Please select the department you want to add participant: 
1. Admin
2. HR
3. Normal
4. Back to Main Menu

Selection: 3
normal's Department
UserID: 85 [ Name: Andrew, Department: normal ]
UserID: 86 [ Name: Jacky, Department: normal ]
UserID: 90 [ Name: Baoky, Department: normal ]

Current Selected Participant :

Usage:
Type exit to return to main menu
Type remove userid to remove participant
Type add userid to add participant

Selection:

问题是:我希望能够让用户添加任意​​数量的参与者,直到他决定“退出”到主菜单,但我如何将其存储在字符串参与者中。

如何检测用户输入是“删除用户 ID”或'添加用户ID'然后获取用户ID

例如加86然后他加 90

然后他决定去掉90

字符串如何跟上它

下面是我的代码:

do
{
cout << "Current Selected Participant : " << participant << endl;
cout << "" << endl;

do
{
if(counter>0)
{
//so it wont print twice
cout << "Usage: " << endl;
cout << "Type exit to return to main menu" << endl;
cout << "Type remove userid to remove participant" << endl;
cout << "Type add userid to add participant" << endl;
cout << "" << endl;
cout << "Selection: ";
}

getline(cin,buffer);
counter++;
}while(buffer=="");




if(buffer.find("remove"))
{
str2 = "remove ";
buffer.replace(buffer.find(str2),str2.length(),"");

if(participant.find(buffer))
{
//see if buffer is in participant list
buffer = buffer + ",";
participant.replace(participant.find(buffer),buffer.length(),"");
}
else
{
cout << "There no participant " << buffer << " in the list " << endl;
}
}//buffer find remove keyword


if(buffer=="exit")
{
done=true;
}
else
{
sendToServer = "check_account#"+buffer;

write (clientFd, sendToServer.c_str(), strlen (sendToServer.c_str()) + 1);
//see if server return found or not found
readFromServer = readServer (clientFd);

if(readFromServer=="found")
{
//add to participant list
participant += buffer;
participant += ",";
}

}//end if not exit

}while(done!=true);

一些用户建议我存储在一个字符串集中,我如何存储在一个字符串集中,以及我如何让终端能够识别选择中的关键字,如'remove'和'add'

然后获取由空格分隔的用户 ID。

接下来是如何删除 if i 存储在字符串集中以及如何将新值插入。

最佳答案

不要将其存储在字符串中。将其存储在允许轻松插入和删除的集合中,例如 std::set<int> .该过程完成后,您可以将集合转换为您认为需要的任何表示形式。

这是一个非常简单的例子(没有检查它是否编译和运行;留给读者作为练习!)

void handle_command(const std::string& command, std::set<std::string>& userids)
{
if (command.substr(0, 4) == "add ")
{
std::string uid = command.substr(4);

if (userids.find(uid) == userids.end())
userids.insert(uid);
else
std::cout << "Uid already added" << std::endl;

return;
}
else
throw std::exception("Unsupported command, etc");
}

关于C++我如何做一个添加新值并可以删除现有值的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11986030/

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