Search code examples
c++stringcompiler-errorssubstring

When I try to use string.insert() it tells me there is a length error at memory location... How do I fix this?


#include <iostream>
#include <string>
#include <cstring>
using namespace std;

string empty(string str) {
    
    for (int i = 0;i < str.length();i++) {
        if (str[i] == ' ') {
            
              str.insert(str[i], ",");
            
        }
        cout << str[i];
    }
    return st;
}

int main() {
    string str;
    getline(cin, str);
    empty(str);

    return 0;
}

I tried string.resize, or in loop i<str.max_size, str.size and str.replace, I tried to add +1 to size or to length but nothing works.


Solution

  • You are getting a runtime error because the 1st parameter of insert() expects an index but you are passing it a char instead, and your input string happens to contain a character whose numeric value is larger than the string's length.

    After fixing that, you will then run into a new problem with the loop getting stuck running endlessly once an insert occurs. This is because you are inserting the comma character BEFORE the current space character. So each insert pushes the current space character (and subsequent characters) forward 1 position. Then the next loop iteration increments i skipping the newly inserted comma character but then finds the same space character again, so it inserts again. And again. And again. Endlessly.

    To prevent that, you would need to incremement i by an extra +1 after an insert to skip the space character.

    Try this:

    void empty(string str) {
        
        for (size_t i = 0; i < str.length(); ++i) {
            if (str[i] == ' ') {            
                str.insert(i, ",");
                ++i;
            }
        }
        cout << str;
    }