-1

This is the link above of the code of printing the number of words. It's running properly but sometimes it's showing the error "out of range", I don't know the reason, can someone please explain why?

#include <iostream>
using namespace std;
int main()
{
    string str;
    getline(cin, str);
    int count = 0;

    for (int i = 0; i < str.length(); i++)
    {
        if (str.at(i) == ' ')
        {
            i++;
        }
        else
        {
            while (str.at(i) != ' ')
            {
                i++;
                if (str.at(i) == str.length())
                {
                    break;
                }
            }
            count++;
        }
    }
    cout << "number of words are : " << count;
}

Online demo

Ch3steR
  • 20,090
  • 4
  • 28
  • 58

2 Answers2

0

Simple answer is:

while (str.at(i) != ' ')

might go out of bound.

Think what would happen if you enter these lines?

Hello!!!!
Hello world!!!

It will hit that while() loop and loop forever.

Why are you getting error sometimes, and not all the times? Because you are causing undefined behavior.

Your if statement is not doing what you think it is doing. It is comparing characters to str.lenght(). So basically you are comparing H, e, l, l and o against str.lenght().

If we look int ASCII char values we get this:

char | decimal value | str.lenght()
-----+---------------+--------------
H    | 72            | 5
e    | 102           | 5
l    | 108           | 5
l    | 108           | 5
o    | 111           | 5
!    | 33            | 5
!    | 33            | 5
!    | 33            | 5

Your line:

if (str.at(i) == str.length())
    break;

should be:

if (i == str.length())
    break;

to compare position in string with string length. Further more you should never use == to check if i against str.lenght() you should use >=, just in case there is a bug in memory somewhere and i skips value of str.lenght().

if (i >= str.length())
    break;
0

Inside the whole loop you are using the expression str.at(i) == str.length(), but I believe it should be I == str.length().

Jonathon S.
  • 1,928
  • 1
  • 12
  • 18