1

I'm solving a little problem and I met an runtime error and I have no idea where is the source of that error. I'm taking a string word and converting it's uppercase consonants to the corresponding lowercase ones by building another string new_word. The error appears at the else if statement.

The error: C++ exception: std::out_of_range at memory location 0x006FF330.

Please help!

int main()
{
    string word, new_word; 
    string::iterator i;
    cin >> word;
    for (i = word.begin(); i < word.end(); i++)
    {
        if (*i != 'A' && *i != 'a' && *i != 'O' && *i != 'o' && *i != 'Y' && *i != 'y' && *i != 'E' && *i != 'e' && *i != 'U' && *i != 'u' && *i != 'I' && *i != 'i')
        {

            if (*i > 'a' && *i <= 'z') 
            {
                new_word.push_back('.');
                new_word.push_back(*i);
            }
            else if (*i > 'A' && *i <= 'Z')
            {
                new_word.push_back(word.at(*i)+32);
            }

        }
    }
    cout << new_word;

    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Ion
  • 81
  • 1
  • 9
  • 2
    `std::out_of_range` tells you that `word.at(*i)` results in an out of range error. So what do you expect that the value of `*i` should be, and why should it correspond to an index of `word`? – t.niese Dec 08 '19 at 11:49
  • 1
    You don’t want to use `*i` as an index into `word`: it is the value you want to access already. – Dietmar Kühl Dec 08 '19 at 11:49
  • i lost my attention =/ – Ion Dec 08 '19 at 11:51

1 Answers1

2

It seems you mean

new_word.push_back( *i +32);

instead of

new_word.push_back(word.at(*i)+32);

Pay attention to that instead of using magic numbers like 32 you could use the standard C function tolower declared in the header <cctype>. For example

#include <cctype>
//...
new_word.push_back( std::tolower( ( unsigned char )*i ) );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335