Home > OS >  String is out of range
String is out of range

Time:11-20

The task is interchange two parts of a word, which contains the dash (i.e we have 1237-456 but should transform it into 456-1237). Here`s my code, it runs but doesnt shows results as a string is out of range and i dk why. It happens in the 1st for, the second iteration ends in the error it happens when strlen is 5 and more. The code:

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

int main()
{
    int u = 0, y = 0;
    string first, second;
    int i = 0;
    string word;
    cout << "Enter the text: " << endl;
    getline(cin, word);
    int l = size(word);
    int f = word.find('-');
    cout << "The word has " << l << " characters" << endl << endl;
    for (int i = 0; i < f; i  ) {
        first[i] = word[i];
    }
    for (int i = f   1; i < l; i  ) {
        second[y] = word[i];
        y  ;
    }
    cout << endl << second << " - " << first << endl;
}

CodePudding user response:

first and second will not have memory allocated to them. They are initialized as strings of size 0. And for this case I would just use iterators instead of indices (though they could work too, but then you need more manual work to allocate enough room for the target strings and all). All in all I think your code is mixing 'c' and 'c ' style a bit so here is my example:

#include <algorithm> // for find
#include <iostream>

// #include <cstdlib> // <<== this is "c" not C  
// using namespace std; <<== unlearn this

int main()
{
    std::string word{ "Mississippi-delta"};

    // std::string has a lenght function use that
    std::cout << "The word has " << word.length() << " characters\n";
    
    // "it" will be an iterator to the location of '-' (if any)
    auto it = std::find(word.begin(), word.end(), '-');
    
    // it points (beyond) the end of the word if no '-' is found
    if (it == word.end())
    {
        std::cout << "no '-' found in word";
    }
    else
    {
        std::string first{ word.begin(),it };
          it; // skip '-'
        std::string second{ it,word.end() };

        std::cout << second << "-" << first << "\n";        
    }

    return 0;
}

CodePudding user response:

Instead of accessing the elements of first and second, just try using .push_back() to add characters from word.

  • Related