0

Given the string IP as input

int index, i=0;
string substr;
while(i!=-1 && IPv4){
            index=IP.find(".",i+1);
            substr=IP.substr(i,index);
            cout << substr << " found at index " << index << " with i= "<<i << endl;
            i=index;
        }

Input: "172.16.254.1"

Expected output:

172 found at index 3 with i= 0
.16 found at index 6 with i= 3
.254 found at index 10 with i= 6
.1 found at index -1 with i= 10

Resulting output:

172 found at index 3 with i= 0
.16.25 found at index 6 with i= 3
.254.1 found at index 10
.1 found at index -1 with i= 10

So the values the algorithm uses should be correct and yet I get the wrong substring.

Any input would be appreciated

Mr. Llama
  • 20,202
  • 2
  • 62
  • 115
someCoder
  • 185
  • 3
  • 15
  • 2
    Possible duplicate of [How to use string.substr() function?](https://stackoverflow.com/q/2477850/608639) – jww Jul 06 '18 at 01:02

1 Answers1

4

substr takes an index and a length.

Also, it's probably not a good idea to name your variable the same as a member function. You probably want:

ip_chunk = IP.substr(i, index - i);
scohe001
  • 15,110
  • 2
  • 31
  • 51