-1

The code has a header, implementation, and main files. It is supposed to increment the ASCII value of all characters in the string then return the character value associated with that ASCII value.

The code in question is as follows:

    for(int i = 0; i < sizeof(letters); i++)
    {
        if ((int)letters.at(i) >= (int)'a' && (int)letters.at(i) <= (int)'z')
        {
            letters.at(i) = (((letters.at(i) - 'a') + 1) % 26 + 'a');
        }

        else if ((int)letters.at(i) >= (int)'A' && (int)letters.at(i) <= (int)'Z')
        {
            letters.at(i) = (((letters.at(i) - 'a') + 1) % 26 + 'A');
        }
    }

Unhandled exception at 0x750A3DB2 in HomeworkNine.exe: Microsoft C++ exception: std::out_of_range at memory location 0x00EFF7E8. occurred

I do not see where the out of bounds is, since I thought the modulus would take care of that.

ADS_Fibonacci
  • 45
  • 1
  • 6

1 Answers1

5

sizeof(letters) is only right if letters is a plain array of char, which it cannot be because plain arrays don't have at member function. at member functions in the C++ standard library compare with size() for random-access sequences and throw std::out_of_range if the index is not less than size(). You need to replace sizeof(letters) with letters.size().

Note that the upper case branch has a bug that is does -'a' and then +'A'.

Those casts to int are unnecessary because the compiler does them for you (or unsigned if char is unsigned on your platform). The built-in arithmetic operators and comparisons work only on int or larger types, see Integral promotion.

Alternative C++11 version:

std::string letters("abc..zABC..Z");
for(auto& c : letters) {
    if(std::isalpha(c))
        c += std::tolower(c) != 'z' ? 1 : ('a' - 'z');
}
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271