Mid-Beginner C++ problem

In this code, the do-while seems not to work properly. It just keeps on repeating. I'd really like you to help me out with this.
Here it is:


//Write a program that will ask the user to input a word that is at
//least 5 characters in length.
//Once a valid word has been inputted, ask the user to input a
//character. The program will calculate the number of times this
//inputted character appears in the word and output the result.

#include <iostream>
#include <string>
using namespace std;

int main()
{
string word = "";

do
{
cout<<"Enter a word that has at least 5 characters: ";
cin>>word;
}while (word.length() < 5);

char searchCh = '0';
cout<<"Enter a character and the program will tell you how many times it appears in '"<<word<<"'."<<endl;
cin>>searchCh;

int counter = 0;

for (int i = 0; i <= word.length();i++)
{
char ch = word.at(i);

if (searchCh == ch)
{
counter++;
}
}
cout<<"The number of "<<searchCh<<"'s in the word '"<<word<<"' is "<<counter<<endl;
}
Hey, please use code tags for your code, would be much easier to read - http://www.cplusplus.com/articles/jEywvCM9/

The do-while loop works perfectly fine. It keeps on repeating until you meet the condition, which is enter a word that is at least 5 characters in lenght

The problem is the for loop. Specifically this - i <= word.length();

Since it's <= and not <. The loop will go out of bound. Because if word is of say, 6 lenght. The loop will go from 0-6, But that's 7 characters. String works like an array and the index starts with 0. So a string of 6 character lenghts goes from 0-5. That's why you want i < word.length();
Last edited on
Thanks for the useful info and for solving the problem :)
Topic archived. No new replies allowed.