954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

End a for loop

I have 2 loops like below. In the second loop I am searching a string if I can find the
"*" character.
This loop will loop 100 times but what I am wondering is that if you wont find the character "*" in the string str, is is possible to end or go out of this loop, so is wont need to loop to 100 ?
In this case the second loop will only iterate i2 = 0 since there is no "*" found and not go to 1,2,3 up to 100.
Thanks..

for( int i = 0; i < 5; i++)	//loop 1	
{	

std::string str= "Number1 - Number2";


    for( int i2 = 0; i2 < 100; i2++)	//loop2
    {
	std::string::size_type index = str.find("*", 0);
	if( std::string::npos != index )
	{

	    //Do some stuff if a "*" was found in str

	}
    }




}
Jennifer84
Posting Pro
564 posts since Feb 2008
Reputation Points: 10
Solved Threads: 1
 

Er... I'm not exactly sure what you're asking, but it sounds like you may be searching for the break command. Having break; anywhere in a loop will end the current iteration and end the loop. If that's not it, then continue; will end the current iteration, but instead of breaking out of the loop, control will return to the top of the loop, and another iteration will be executed (assuming the conditional is still true).

CoolGamer48
Posting Pro in Training
401 posts since Jan 2008
Reputation Points: 77
Solved Threads: 40
 
for( int i = 0; i < 5; i++)	//loop 1	
{	

std::string str= "Number1 - Number2";


    for( int i2 = 0; i2 < 100; i2++)	//loop2
    {
	std::string::size_type index = str.find("*", 0);
	if( std::string::npos != index )
	{

	    //Do some stuff if a "*" was found in str
	    break;
	}
    }




}
ivailosp
Junior Poster
129 posts since Apr 2008
Reputation Points: 21
Solved Threads: 22
 

Thank you. I managed it to work when I changed the place for the break like below.

for( int i = 0; i < 5; i++)	//loop 1	
{	

std::string str= "Number1 - Number2";


    for( int i2 = 0; i2 < 100; i2++)	//loop2
    {
	std::string::size_type index = str.find("*", 0);

	if( index > str.length())
	{
		break;	
         }


	if( std::string::npos != index )
	{

	    //Do some stuff if a "*" was found in str
	    //break;
	}
    }




}
Jennifer84
Posting Pro
564 posts since Feb 2008
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You