获取包含字符和整数的字符串,并分别使用C ++

问题描述 投票:0回答:1

我需要输入像这样的字符串:

add 4
cancel 200
quit

并将它们用作命令。

例如:获得add [n]会告诉程序使用add函数并使用int 4的值。

我如何一次输入所有这样的字符串,并多余地使用命令字和int?

c++ string get getline
1个回答
-1
投票

具体来说,这取决于输入来自何处,但是通常我会通过解析来处理它。像这样的东西:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

// Prototype
void runCommand(std::string action, int amount);
void parseCommand(std::string rawCommand, std::vector<std::string>& command);

int main()
{
    std::vector<std::string> command;       // Vector of strings that will take the command
    std::string stringInput;

    parseCommand(stringInput, command);    // Separate the raw command into different strings (command[0] and command[1])
    runCommand(command[0], stoi(command[1])); // Run the command

    return 0;
}

void runCommand(std::string action, int amount)
{
    if (action == "add")  // If the command is to add, call the add function
    {
        // add(amount);
    }
    else if (action == "cancel")   // If the command is to cancel, call the cancel function
    {
        // cancel(amount);
    }
}

// This function will take the string rawCommand, parse it into different strings,
// and put the parsed string into the vector command. Command is taken by reference
// so it can modify the original vector object.
void parseCommand(std::string rawCommand, std::vector<std::string>& command)
{   
    std::stringstream stringStream;         // Convert the string input to a std::stringstream
    std::string stringTransfer;             // This string will be a part of the command input

    stringStream << rawCommand;            // Converting the stringInput into a stringStream

    // parse the line separated by spaces
    while (std::getline(stringStream, stringTransfer, ' '))
    {
        // put the command in the vector
        command.push_back(stringTransfer);
    }
    // Clear the command to get it ready for the next potentintial command
    command.clear();
}

当然,您必须声明所有变量。我本人是菜鸟,所以其他人可能会有更好的方法。

© www.soinside.com 2019 - 2024. All rights reserved.