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