for loop

Hi I have a problem with this loop, I don't know what is exactly wrong. Here it is:

for (int=0;i<=phrase.size();++i)
{
cout<<"Character at position" <<i<< "is" <<phrase[i] <<endl;
}

When i put this in a code well written, the program crashes and says " string suscript out of range" I know that i it should be unsigned int=0 and it has to be with <= operator, that it shoulb be <. But I don't know

Thank you so much !
First you need to declare i in the for loop, as in for(int i=0;...

and second I think you are incrementing but not storing the increment. as in ...i++) rather than ...++i)

as for other peices, phrase is stored as a character array right?
oh no sorry, it is declared i, i made a mistake so it is already int i=0.
I compare with other program about the increment and it is the same "++i" the only 2 differences are with <=, in the other program is < and in the declaration of i is " unsigned int i =0 "
somebody there?
In an array (or any other indexable standard container such as std::string), the indices go from 0 to size-1.
In light of that, your loop condition is wrong.
Last edited on
So... the condition is wrong because it is <= 0 , so never is going to be -1?
thanks in advance!
No, those "mistakes" aren't mistakes. ++i does (as far as this case is concerned) the exact same as i++.

What type of variable is "phrase"? I'm guessing a C++ string? If so: replace "<= phrase.size()" by "< phrase.size()". Remember this: an array (yes, a string is an array) starts at [0]. This means the last element is saved at size()-1. E.g.: 10 elements are saved on spots 0 to 9.
Ok!! I think I got it now... the condition should be < instead of <= because the last element is saved in -1.....right?
thanks!
Topic archived. No new replies allowed.