Класс разбитой строки C ++ в функции, не использующей strtok () - PullRequest
0 голосов
/ 21 октября 2018

У меня есть функция конструктора по умолчанию, которая принимает переменную класса строки (не char*) и должна маркировать эту строку разделителем, который в моем конкретном случае является запятой.Поскольку я использую строковый класс, я не могу, насколько я знаю, использовать strtok(), потому что он ожидает char* в качестве ввода, а не строковый класс.Учитывая приведенный ниже код, как я могу разбить строку на более мелкие строки, учитывая, что первые два токена являются строкой, третий - входным, а четвертый - double?

private string a;
private string b;
private int x;
private double y;

StrSplit::StrSplit(string s){
  a = // tokenize the first delimiter and assign it to a
  b = // tokenize the second delimiter and assign it to b
  x = // tokenize the third delimiter and assign it to x
  y = // tokenize the fourth delimiter and assign it to y
}

1 Ответ

0 голосов
/ 21 октября 2018

Попробуйте ниже исходный код: ( протестируйте его онлайн )

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

std::string a;
std::string b;
int x;
double y;

std::vector<std::string> split(const std::string& s, char delimiter)
{
   std::vector<std::string> tokens;
   std::string token;
   std::istringstream tokenStream(s);
   while (std::getline(tokenStream, token, delimiter))
   {
      tokens.push_back(token);
   }
   return tokens;
}

int main()
{
    std::string str = "hello,how are you?,3,4";
    std::vector<std::string> vec;
    vec = split(str, ',');

    a = vec[0];
    b = vec[1];
    x = std::stoi(vec[2]);              // support in c++11
    x = atoi(vec[2].c_str());
    y = std::stod(vec[2].c_str());      // support in c++11
    y = atof(vec[2].c_str());

    std::cout << a << "," << b << "," << x << "," << y << std::endl;

}

Вывод будет:

hello,how are you?,3,3
...