• Advertisement
Sign in to follow this  

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

This topic is 4891 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement