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;
}
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 ) );