-2

this is the error :

Unhandled exception at 0x00007FFD16B7FE7C in Project1.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0000000B2FAFF760.

here is the code :

#include <iostream>
using namespace std;



int main() {

    
    string word;
    
    cin >> word;

    cout << word.size() << endl;

    
    for (int i = 0; i <= word.size(); i++)

        cout << word.at(i) << endl;




    return 0;
}

im also still not sure where the code breaks it, it just takes me to a weird window with A LOT OF LINES that i have no idea what they mean.

i tried debugging, rebuilding, trying some alternative ways to write the code that i know of and nothing worked, like the code is so simple HOW AM I OUT OF MEMORY XD.

alfC
  • 14,261
  • 4
  • 67
  • 118
  • 3
    If `word.size()` is `0`, how many characters does your program try to print? – Drew Dormann Apr 19 '23 at 19:48
  • 3
    Loops using `<=` as a terminating condition are frequently wrong, as this one is. – Paul Sanders Apr 19 '23 at 19:49
  • 1
    _it just takes me to a weird window with A LOT OF LINES that i have no idea what they mean_ Could that be a stack trace? Those are usually useful, since they show you where the error occurred. – Paul Sanders Apr 19 '23 at 19:51
  • If you had used `[]` instead of `.at` it would have "worked." The former accepts indexes one more than the latter. And it's legal for reading. – doug Apr 19 '23 at 20:08
  • General rule of thumb: If you see a `<=` in the exit condition of a loop, examine the loop. You probably have a bug. – user4581301 Apr 19 '23 at 20:23

2 Answers2

3

In this for loop

for (int i = 0; i <= word.size(); i++)

    cout << word.at(i) << endl;

the variable i is being changed in the range [0. word.size()]. However the member function at throws exception out_of_range when its argument is equal to or greater than the value returned by the member function size().

So change the for loop like

for (int i = 0; i < word.size(); i++)

    cout << word.at(i) << endl;

Pay attention to that opposite to the member function at the index of the subscript operator may be equal to the value of size().

That is you may write

for (int i = 0; i <= word.size(); i++)

    cout << word[i] << endl;

though there is no great sense to use the index equal to the value of size().

To avoid such a mistake it is better to use range-based for loop like

for ( char c : word )

    cout << c << endl;

or

for ( const auto &c : word )

    cout << c << endl;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

Try with:

for (int i = 0; i < word.size(); i++)

If you have size elements in word, the loop will run size times, not size + 1 times.

alfC
  • 14,261
  • 4
  • 67
  • 118