C++ 如何执行添加新值并可以删除现有值的循环
C++ How do I do a loop that add in new value and can delete existing value
感谢您阅读这个问题。
基本上,我正在尝试编写可以实现以下内容的代码:
用户将看到如下所示的详细信息列表
终端视图:
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);
一些用户建议我存储在字符串集中,如何存储在字符串集中,以及如何使终端能够识别选择中的"删除"和"添加"等关键字
然后获取用空格分隔的用户 ID。
接下来是如何删除我是否存储在字符串集中以及如何推送新值。
不要将其存储在字符串中。将其存储在易于插入和删除的集合中,例如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");
}
相关文章:
- 如何从使用 for 循环中的矢量大小的矢量中删除元素
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- 删除功能不适用于串行通信后多个循环中的多个实例
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- c++ 循环访问对象列表并删除对象
- 循环以从字符数组中删除过多的空格 (C++)
- C++循环链表删除,计数从下一个节点开始
- c++ 在循环中删除迭代器(映射的映射)
- 遍历 STL 映射(集/多集)的最佳方法,同时元素可能会在循环期间被删除并重新插入?
- 循环依赖:无法删除不完整的类型
- 如何在每次循环迭代期间生成向量,存储数据,然后删除该向量?
- 我写了一个函数来删除循环链接列表中的第 1 个节点,但输出显示无限次"55 44 33 22 11 99",那么我该如何解决呢?
- 删除循环链接列表中的项目
- 删除循环双向链表中的节点
- 基于条件语句删除循环中的矢量元素
- 删除循环内矢量的元素
- 删除循环中Vector的元素
- 删除循环列表中的节点时崩溃
- 删除循环链表中的节点
- 删除循环内存泄漏