Jump to content
  • Advertisement
Sign in to follow this  
grim_reaper7

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

This topic is 5065 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
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!