Unexpected int decrement during For Loop

Hi there,

I'm trying to make a simple script to split a delimited string, by checking each char in the input; if it is a '/' move to the next string in the array, if it is a char add to the string in the array.
My problem here is that about halfway through the for loop, my 'delimit_count' is decrementing? So it isn't catching when there are too many '/'s in the input string, and also appends to the wrong string in the array.
I'm very new to c++, just wondering why this would be? While debugging, 'delimit_count' seems to decrease by one, only occasionally, at this line:
 
str_result[delimit_count].append(1,str_input[input_pos]);


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <stdlib.h>
using namespace std;

string doSplit(string str_dateinput);

int main(int argc, char**argv) {
    
    
    string input;
    cout << "Enter a string sequence (A/B/C):";
    cin >> input;
    cout << doSplit(input);
          
    return 0;
}

string doSplit(string str_input) {
    
    string str_result[2];
    int input_pos;
    int delimit_count=0;

    for (input_pos=0;(input_pos<=str_input.length());input_pos++){
        if (str_input[input_pos]=='/'){
            if (++delimit_count>2) {
                cout << "too many delimiters";
                break;
            }
        } else {
            str_result[delimit_count].append(1,str_input[input_pos]);
        }
    }
    return "A: " + str_result[0] + "\nB: " + str_result[1] + "\nC: " +str_result[2];
}
Last edited on
str_result is an array of size 2. You have to make it size 3 if you want to store 3 strings.

input_pos<=str_input.length()
should probably be
input_pos<str_input.length()
otherwise you will append a null character '\0' at the end of the last string, which you probably don't want to do.
Gah! So simple .. I would've thought it'd throw an exception for referencing an invalid array element?
Regardless, thanks very much :)
Topic archived. No new replies allowed.