Расщепление строки разными разделителями - PullRequest
0 голосов
/ 24 марта 2020

Имеет следующий тип ввода:

add name, breed, birthDate, vaccinationsCount, photograph

(например, add boo, yorkshire terrier, 01-13-2017, 7, boo puppy.jpg)

Я хочу разделить эту строку, чтобы получить из нее мои параметры, и она не работала .

Мой код выглядел так:

getline(cin, listOfCommands);
string functionToApply = listOfCommands.substr(0, listOfCommands.find(" "));
int position = listOfCommands.find(" ");
listOfCommands.erase(0, position + 1);
cout << listOfCommands;
if (functionToApply == "exit")
    break;
else if (functionToApply == "add")
{
    position = listOfCommands.find(", ");
    string name = listOfCommands.substr(0, position);
    listOfCommands.erase(0, position + 1);
    position = listOfCommands.find(", ");
    string breed = listOfCommands.substr(0, position);
    listOfCommands.erase(0, position + 2);
    position = listOfCommands.find(", ");
    string birthDate = listOfCommands.substr(0, position);
    listOfCommands.erase(0, position + 2);
    position = listOfCommands.find(", ");
    string nrShorts = listOfCommands.substr(0, position);
    listOfCommands.erase(0, position + 2);
    string photo = listOfCommands;
}

Может кто-нибудь помочь мне, пожалуйста?

Ответы [ 2 ]

1 голос
/ 24 марта 2020

Для этого примера я использую std :: getline с пользовательским разделителем, std :: stringstream , чтобы помочь разобрать вводимый поток, и std :: vector для сохранения параметров (если вы предпочитаете, вы можете назначить их переменным, которые вы для них создали):

Живой пример

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

int main() {

    std::string listOfCommands, temp, command;
    std::vector<std::string> args; //container for the arguments

    //retrieve command
    getline(std::cin, command, ' ');

    if (command == "add") {

        getline(std::cin, listOfCommands);     
        std::stringstream ss(listOfCommands);

        while (getline(ss, temp, ',')) { //parse comma separated arguments

            while (*(temp.begin()) == ' ')
                temp.erase(temp.begin()); //remove leading blankspaces

            args.push_back(temp); // add parameter to container
        }

        //test print
        for (std::string str : args){
            std::cout << str << std::endl;
        }
    }
    return 0;
}

Вход:

add boo, yorkshire terrier, 01-13-2017, 7,    boo puppy.jpg

Выход:

boo
yorkshire terrier
01-13-2017
7
boo puppy.jpg
0 голосов
/ 24 марта 2020

Попробуйте regex_token_iterator :

#include <regex>

const int split_constant = -1;
std::vector<std::string> args(
  std::sregex_token_iterator(listOfCommands.begin(), 
                             listOfCommands.end(), 
                             std::regex(", "), 
                             split_constant),
  std::sregex_token_iterator());

Конечно, вам не нужно сохранять токены в векторе, вы также можете просто перебрать их:

auto iter = std::sregex_token_iterator(listOfCommands.begin(), 
                                       listOfCommands.end(), 
                                       std::regex(", "), 
                                       split_constant);
const string functionToApply = *iter++;
if (functionToApply == "exit") break;
const string name  = *iter++;
const string breed = *iter++;
// etc.
...