phrase.size() how do i use this correctly?

Started by
1 comment, last by grim_reaper7 19 years, 4 months ago
ok, i have spent a lot of time trying to figure y error is saying the phrase.size() is being called wrong, it will compile but when runs it is an infinited loop
#include <iostream>
#include <string>

using namespace std;

int main()
{
	int pause;
	string word1 = "Game";
	string word2("Over");
	string word3(3, '!');

	string phrase = word1 + " " + word2 + word3;
	cout<<"The phrase is: "<<phrase<<"\n\n";
	cout<<"The phrase has "<<phrase.size()<<" characters in it\n\n";
	cout<<"The character at position 0 is: "<<phrase[0]<<"\n\n";

	phrase[0] = 'L';
	cout<<"The new phrase is now: "<<phrase<<"\n\n";
	for(int i =0; phrase.size(); ++i)
		cout<<"Character at position: "<<i<<" is :"<<phrase<<"\n\n";
	    
	cout<<"\n\nThe sequence 'Over' begins at location "<<phrase.find("Over")<<endl;
		if (phrase.find("eggplant") == string::npos)
			cout<<"'eggplant' is not in phrase\n\n";
	phrase.erase(4, 5);
	cout<<"The phrase is now: "<<phrase<<endl;
	phrase.erase(4);
	cout<<"The phrase is now: "<<phrase<<endl;
	phrase.erase();
	cout<<"The phrase is now: "<<phrase<<endl;

	if (phrase.empty())
		cout<<"\nThe phrase in no more\m";
	cin>>pause;
	return 0;

}
please help me, i have googled and looked in some books and am not understanding..thnx
Grim_reaper7Lamp Geekz
Advertisement
Here's your problem

	for(int i =0; phrase.size(); ++i)		cout<<"Character at position: "<<i<<" is :"<<phrase<<"\n\n";


here's the solution
for(int i =0; phrase.size() > i; ++i)		cout<<"Character at position: "<<i<<" is :"<<phrase<<"\n\n";


What's happening is that your never get a 'false' in your test in your for loop. It's always non-zero, where zero is false. Adding the test solves your problem.
damn, with such an easy answer bring discouragement, knowing i went over that a hundreed times!

thnx
Grim_reaper7Lamp Geekz

This topic is closed to new replies.

Advertisement