Sign in to follow this  
grim_reaper7

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

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[i]<<"\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
Here's your problem


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


here's the solution

for(int i =0; phrase.size() > i; ++i)
cout<<"Character at position: "<<i<<" is :"<<phrase[i]<<"\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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this