Tuesday, July 28, 2009

C++ help!!?

2. Write a function that prints out a welcome banner (that prints out a welcome message) in the following format:





Welcome, User #1, to the System! // the first time the banner is printed out





Welcome, User #2, to the System! // the second time the banner is printed out





...





Welcome, User #45, to the System! // the 45th time the banner is printed out





The function will contain a static int variable that will keep track of the number of times the banner has been printed out.





#include %26lt;iostream%26gt;


using namespace std;





void showStatic();





int main()


{


for (int count = 0; count %26lt; 1000000000; count++)


showStatic();


return 0;


}





void showStatic()


{


static int statNum;





cout %26lt;%26lt; "Welcome, User# \n";


cout %26lt;%26lt; "to the System!" %26lt;%26lt; statNum %26lt;%26lt; endl;


statNum++;


}





I don't even know what I'm doing!! Can you please help me %26amp; fix my code?





Thanks

C++ help!!?
currently, your sentences show up all at once because they are in a loop:





for (int count = 0; count %26lt; 1000000000; count++)





this calls the function showStatic() 1000000000 times (which does not work, btw, because count is an Integer, and integers cannot become that large).





anyway, if you want the number to show up just once, you have to remove the loop. Or reduce the 1000000000 to 1:





for (int count=0; count%26lt;1; count++)


showStatic();





If you want to call showStatic() five times, you can change the loop like this:


for (int count=0; count%26lt;5; count++)


showStatic();





Or, alternatively, you can just call showStatic 5 times:


showStatic();


showStatic();


showStatic();


showStatic();


showStatic();





(but that's a bit ugly, the loop is nicer and more elegant).
Reply:change


void showStatic()


{


static int statNum;





cout %26lt;%26lt; "Welcome, User# \n";


cout %26lt;%26lt; "to the System!" %26lt;%26lt; statNum %26lt;%26lt; endl;


statNum++;


}


to


void showStatic()


{


static int statNum;





cout %26lt;%26lt; "Welcome, User#"%26lt;%26lt; statNum;


cout %26lt;%26lt; "to the System!"%26lt;%26lt; endl;


statNum++;


}
Reply:Your code looks totally fine however you should drop your "cout" lines and replace them with:





cout %26lt;%26lt; "Welcome, User#" %26lt;%26lt; ++statNum %26lt;%26lt; "to the System" %26lt;%26lt; endl;
Reply:I've been waiting for a C++ expert to show up as I only know C. But as they are all asleep:





Are you sure about your cout statement?? Is the variable statNum really going to print the number in the right place like that? I don't see a problem with your loops - except that the main() function is going to free run through squillions of iterations and give you screensful of Welcomes. Put an input statement before the showStatic() to keep it to one at a time.


No comments:

Post a Comment