0

I worked a little bit with javascript and I decided to work on a function that will work similar to str.split(), but in C++. The next code I wrote shows me this error:

no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=char, _Alloc=std::allocator]" matches the argument list -- argument types are: (char *) -- object type is: std::vector>

#include <iostream>
#include <cstring>
#include <vector>

using namespace std;

vector<char> split(char str[], char spliter[]){
    unsigned i=0;
    vector <char> output;
    char *p = strtok(str, spliter);
    do{
        output.push_back(p);
        p = strtok(NULL, spliter);
    }while(p != NULL);
    return output;
}

int main()
{
    char s[51];
    strcpy(s, "I have a cake");
    split(s, " ");
}
KaZMa
  • 35
  • 6
  • 6
    A vector of chars can't hold strings. – tkausl Apr 21 '19 at 16:22
  • It looks like you are trying to reinvent Boost.Split: https://www.boost.org/doc/libs/1_70_0/doc/html/string_algo/usage.html#id-1.3.3.5.9 – Eljay Apr 21 '19 at 16:30
  • Bold assumption from both of you that I actually understand wtf I am doing. I dont want to be mean to you, I'm just making fun of my limited knowledge of C++. But I actually need something more precise to understand, like what I need to use, "vector output"? or do I need to change the whole code? I also learned about how char* works today and I still dont understand them very well. – KaZMa Apr 21 '19 at 16:44
  • I don't know if this is really a duplicate but there are many approaches to splitting strings in the answers to this question: https://stackoverflow.com/questions/236129/how-do-i-iterate-over-the-words-of-a-string – Galik Apr 21 '19 at 16:55
  • 1
    Yes, using `std::vector` is the right idea. I would also get rid of the `char` arrays and use `std::string` instead. It has a [find method](https://en.cppreference.com/w/cpp/string/basic_string/find) to find your delimiter. – super Apr 21 '19 at 17:41

0 Answers0