Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String incompatibility issues c++

I am trying to create a function that will take in a long string with " " and "," dividing different elements gained from a text file. "," represents a new line and " " represents the end of a number in the line. once split the strings should be part of an array.

string* splitstr(string text, string deli = " ")
{
    int start = 0;
    int end = text.find(deli);
    string *numbers[end];
    for (int i = 0; end != -1; i++)
    {
        numbers[i] = text.substr(start, end - start);
        start = end + deli.size();
        end = text.find(deli, start);
    }
    return numbers;
}

However I am facing a problem where I get this:

cannot convert 'std::string**' {aka 'std::__cxx11::basic_string<char>**'} to 'std::string*' {aka 'std::__cxx11::basic_string<char>*'} in return

How can I resolve this, or improve my function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I was expecting to be able to store string elements in a string array and make the function return the array. I’m fairly new to programming and I started off with java so this logic might not work in c++.

>Solution :

You should avoid using arrays like this and instead use a vector

like as follows:

std::vector<std::string> splitstr(const std::string & text, const std::string & deli = " ")
{
    int start = 0;
    int end = text.find(deli);
    std::vector<std::string> numbers;
    for (int i = 0; end != -1; i++)
    {
        numbers.push_back(text.substr(start, end - start));
        start = end + deli.size();
        end = text.find(deli, start);
    }
    return numbers;
}

note this will not get the last item in the string if there is not a delimiter after it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading