Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating a string split function in C++ [duplicate]

Possible Duplicate:
Splitting a string in C++

Im trying to create a function that mimics the behavior of the getline() function, with the option to use a delimiter to split the string into tokens. The function accepts 2 strings (the second is being passed by reference) and a char type for the delimiter. It loops through each character of the first string, copying it to the second string and stops looping when it reaches the delimiter. It returns true if the first string have more characters after the delimiter and false otherwise. The position of the last character is being saved in a static variable. for some reason the the program is going into an infinite loop and is not executing anything:

const int LINE_SIZE = 160;
bool strSplit(string sFirst, string & sLast, char cDelim) {
    static int iCount = 0;
    for(int i = iCount; i < LINE_SIZE; i++) {
        if(sFirst[i] != cDelim)
            sLast[i-iCount] = sFirst[i];
        else {
            iCount = i+1;
            return true;
        }
    }
    return false;
}

The function is used in the following way:

while(strSplit(sLine, sToken, '|')) {
    cout << sToken << endl;
}

Why is it going into an infinite loop, and why is it not working? I should add that i'm interested in a solution without using istringstream, if that's possible.

like image 460
Yoav Kadosh Avatar asked Jan 24 '26 20:01

Yoav Kadosh


1 Answers

It is not exactly what you asked for, but have you considered std::istringstream and std::getline?

// UNTESTED
std::istringstream iss(sLine);
while(std::getline(iss, sToken, '|')) {
  std::cout << sToken << "\n";
}

EDIT:

Why is it going into an infinite loop, and why is it not working?

We can't know, you didn't provide enough information. Try to create an SSCCE and post that.

I can tell you that the following line is very suspicious:

       sLast[i-iCount] = sFirst[i];

This line will result in undefined behavior (including, perhaps, what you have seen) in any of the following conditions:

  • i >= sFirst.size()
  • i-iCount >= sLast.size()
  • i-iCount < 0

It appears to me likely that all of those conditions are true. If the passed-in string is, for example, shorter than 160 lines, or if iCount ever grows to be bigger than the offset of the first delimiter, then you'll get undefined behavior.

like image 69
Robᵩ Avatar answered Jan 26 '26 12:01

Robᵩ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!