Issue when writing a simple code using for loops

68 Views Asked by At

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.

2

There are 2 best solutions below

0
alfC On

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.

2
Vlad from Moscow On

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;