C++多个单词命令
multiple word commands C++
我对C++有点陌生,很抱歉,如果这个问题很明显,但我遇到了一些障碍。我想做的是有一个命令提示符来执行某些事情。您输入简单的命令,例如timer down 10
,它将启动计时器倒计时,我已经做得很好。我检测每个单词的方式是这样的:
string cmd1;
string cmd2;
int cmd3;
cin >> cmd1 >> cmd2 >> cmd3;
这工作正常,除了我想使用单个单词的命令,而有了这个系统,我真的做不到。例如,如果我想help
作为命令,当我只想键入 1 个字符串时,它会让我键入 2 个字符串和一个 int。但是我希望有特定的命令,可以是完整的 2 个字符串和一个 int 或只有 1 个字符串。
使用 getline 将整个命令存储在单个字符串中。
String command;
std::getline (std::cin,command);
现在,您可以使用以下代码将命令拆分为标记字。
int counter =0;
string words[10];
for (int i = 0; i<command.length(); i++){
if (command[i] == ' ')
counter++;
else
words[counter] += command[i];
}
您需要使用 getline
读取命令,然后将其拆分为标记。 检查getline
函数,并在谷歌上为标记 c++ 提供分割线。
您可以
逐行读取输入,然后将每行拆分为包含每个命令后跟其参数的std::vector
:
void command_help()
{
// display help
}
void command_timer(std::string const& ctrl, std::string const& time)
{
int t = std::stoi(time);
// ... etc ...
}
int main()
{
// read the input one line at a time
for(std::string line; std::getline(std::cin, line);)
{
// convert each input line into a stream
std::istringstream iss(line);
std::vector<std::string> args;
// read each item from the stream into a vector
for(std::string arg; iss >> arg;)
args.push_back(arg);
// ignore blank lines
if(args.empty())
continue;
// Now your vector contains
args[0]; // the command
args[1]; // first argument
args[2]; // second argument
// ...
args[n]; // nth argument
// so you could use it like this
if(args[0] == "help")
command_help(); // no arguments
else if(args[0] == "timer")
{
if(args.size() != 3)
throw std::runtime_error("wrong number of arguments to command: " + args[0]);
command_timer(args[1], args[2]); // takes two arguments
}
}
}
相关文章:
- 文本文件中的单词链表
- 从命令行c++发送文本文件名
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 在指针的帮助下,文本文件中单词的频率
- 使用QProcess执行命令,并将结果存储在QStringList中
- 数组长度,为什么从命令行获取时不能使用它?
- 如何根据单词在文本中出现的概率输出单词
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- clang整洁10忽略了我的NOLINT命令
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- 如何处理linux终端中带有负号(-)的C++中的命令行参数
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- 使用VS Code和CMake Tools运行自定义命令
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 如何用for循环在c++中生成单词三角形
- 如果键入了单词 "exit",如何在命令 promt 中进行此退出?
- C++多个单词命令