Friday, July 31, 2009

Help with my c++ program running buy 1 debug error?

Ok i have the function running but i need to make it say to use periods between website address if it doesn't str.find(".") or str.rfind("."). I put an else statement to say a string if the first if doesn't get accepted but it comes with a debug error if no periods are entered in cin. heres the function.





//Najib Saliba


//February 8,2008


//String Fling (reverses your website input)


#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


using namespace std;





string reverse(string str)


{


string problem = "Please use periods between address";


int pos = str.find(".");


int pos2 = str.rfind(".");


if (str.find(pos)%26amp;%26amp;str.find(pos2))


return (str.substr(pos2+1, str.length()) + str.substr(pos, pos2-2) + str.substr(0, pos));


else


return problem;


}





int main()


{


string str;


cout %26lt;%26lt;"Enter a web adress starting with www" %26lt;%26lt;endl %26lt;%26lt;"This program will automatically reverse your input" %26lt;%26lt;endl;


getline(cin, str);


cout %26lt;%26lt;reverse(str) %26lt;%26lt;endl;


return 0;


}

Help with my c++ program running buy 1 debug error?
You are doing to many "finds". You already did the finds when you initialized pos and pos2. In the "if" statement just make sure they found something.





string reverse(string str)


{


string problem = "Please use periods between address";





int pos = str.find(".");


int pos2 = str.rfind(".");





if ((pos != string::npos)


%26amp;%26amp; (pos2 != string::npos))


return (str.substr(pos2+1, str.length()) + str.substr(pos, pos2-2) + str.substr(0, pos));


else


return problem;


}
Reply:If there is no period in the address, the find and rfind methods will return the str::npos value, which is not an integer or boolean value.





Instead of


if (str.find(".")%26amp;%26amp;str.find(".")...





You want to use something like





if ( (str.find("."))!= string::npos ) %26amp;%26amp; (str.rfind("."))!= string::npos ) )





I don't have a compiler handy so I may have made a parentheses/syntax error but I think that that is the correct logic.


No comments:

Post a Comment