如果我了解到您需要同时使用cmd
和key
作为单独的输入,但是用户将输入字符串"cmd key"
,则需要分别处理每个字符串,然后一种简单的方法是使用常规std:string
运算符(例如
)将它们读入
>>
std::string cmd,key;
std::cout << "enter command & key: ";
if (!(std::cin >> cmd >> key)) { /* read/validate both cmd & key */
std::cerr << "stream error or use canceled input.\n";
return 1;
}
现在,您同时存储了cmd
和key
,可以使用cmd
最初确定要采取的分支,然后根据key
选择要采取的行动。例如:
if (cmd == "kick") { /* handle cmd "kick" */
if (key == "ball")
std::cout << "kicking the ball.\n";
else if (key == "dog")
std::cout << "kicking the dog.\n";
else
std::cout << "generally kicking the " << key << ".\n";
}
else if (cmd == "pick") { /* handle cmd "pick" */
if (key == "ball")
std::cout << "picking the ball.\n";
else if (key == "dog")
std::cout << "picking the dog.\n";
else
std::cout << "generally picking the " << key << ".\n";
}
else /* otherwise unknown command */
std::cout << "unknown cmd: " << cmd << ".\n";
(注意:,您始终希望处理用户为每个cmd
或key
(或两者)输入无效内容的情况
在一个简短的示例中将其放在一起,您可以:
#include <iostream>
#include <string>
int main (void) {
std::string cmd,key;
std::cout << "enter command & key: ";
if (!(std::cin >> cmd >> key)) { /* read/validate both cmd & key */
std::cerr << "stream error or use canceled input.\n";
return 1;
}
if (cmd == "kick") { /* handle cmd "kick" */
if (key == "ball")
std::cout << "kicking the ball.\n";
else if (key == "dog")
std::cout << "kicking the dog.\n";
else
std::cout << "generally kicking the " << key << ".\n";
}
else if (cmd == "pick") { /* handle cmd "pick" */
if (key == "ball")
std::cout << "picking the ball.\n";
else if (key == "dog")
std::cout << "picking the dog.\n";
else
std::cout << "generally picking the " << key << ".\n";
}
else /* otherwise unknown command */
std::cout << "unknown cmd: " << cmd << ".\n";
}
使用/输出示例
$ ./bin/cmd_select
enter command & key: kick dog
kicking the dog.
使用命令"pick"
:
$ ./bin/cmd_select
enter command & key: pick ball
picking the ball.
使用未知命令:
$ ./bin/cmd_select
enter command & key: shoot dog
unknown cmd: shoot.
您当然可以将cmd
或key
的字符串传递给一个单独的函数,并在该函数中处理您对每个函数的响应,但这只是另一种安排代码以完成相同操作的方式。仔细检查一下,让我知道这是否是您想要的。根据许多修改,我仍然不是100%清楚。
本文链接:https://www.f2er.com/3083428.html