a.sapp
a.sapp

Reputation: 41

Invalid conversion error when splitting string into a string vector

I'm trying to take a string input from the user, split it into individual strings at each white space and store it in a vector. I'm using the first code snippet from this post (It's the second answer to the question) to do the split on the string. These are the errors I get when compiling:

stringTest.cpp: In function ‘int main()’: stringTest.cpp:23:30: error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive] split(input, " ", splitInput); ^

stringTest.cpp:8:17: error: initializing argument 2 of ‘std::vector >& split(std::string&, char, std::vector >&)’ [-fpermissive] vector &split(string &s, char delim, vector &elems) {

I realize what the first error is saying, but can't figure out what's causing the problem, and I have no idea what the second error means.

This is the code I have written (everything outside of main was taken from the linked post):

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

using namespace std;

vector<string> &split(string &s, char delim, vector<string> &elems) {
    stringstream ss(s);
    string item;
    while (getline(ss, item, delim)) {
        elems.push_back(item);
    }
    return elems;
}

int main(){

    string input;
    cin>>input;
    vector<string> splitInput;

    split(input, " ", splitInput);

    for(int i = 0; i < splitInput.size(); i++){
        cout<< splitInput.at(i) << endl;
    }

    return 0;
}

Upvotes: 1

Views: 135

Answers (1)

gsamaras
gsamaras

Reputation: 73366

Change this

split(input, " ", splitInput);

to this

split(input, ' ', splitInput);

since the prototype of the function is:

vector<string> &split(string &s, char delim, vector<string> &elems) ;, which requests for a char as the second argument, NOT a string.

" " is a string-literal which has type const char[2], while ' ' is a character, which has type char.

You can also check this question: What is the type of string literals in C and C++?

Upvotes: 1

Related Questions