Click to See Complete Forum and Search --> : Could someone help me compress this code a little?


Xaro
March 24th, 2007, 03:24 PM
Hey, I just wrote this program when messing about with the FOR and IF commands and I want to know if someone could help me make it look less....well, make it more efficient if you understand what I mean. Thanks in advance.


#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
string name;
string quit; // Just using this to quit the program.
string correct;
string wrong;
cout << "Please enter your name: ";
cin >> name; // This is where you put a string into the name variable.
cout << "Your name is " << name; cout << ".\n"; // Dumps the variable contents of name to the screen.
restart: // Restart point.
cout << "Please type Quit and press enter. ";
cin >> quit;
if (quit == "Quit") // If the user types "quit".
{
cout << "Thankyou, please type Exit "; // Print message.
cin >> correct;
if (correct == "Exit") // If user types "exit".
{
goto exit; // Go to point "exit:"
}
else // If the user did NOT type "exit"
goto restart;
}

else // If the user did NOT type "quit"
cout << "You did not type Quit! .\n";
goto restart; // Go back!
exit: // Point exit:.
return 0;

}

TheCPUWizard
March 24th, 2007, 04:11 PM
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
string name;
string quit; // Just using this to quit the program.
string correct;
string wrong;
cout << "Please enter your name: ";
cin >> name; // This is where you put a string into the name variable.
cout << "Your name is " << name; cout << ".\n"; // Dumps the variable contents of name to the screen.
int done = 0;
while (!done)
{
cout << "Please type Quit and press enter. ";
cin >> quit;
if (quit == "Quit") // If the user types "quit".
{
cout << "Thankyou, please type Exit "; // Print message.
cin >> correct;
if (correct == "Exit") // If user types "exit".
{
done = 1;
}
}
else
{
cout << "You did not type Quit! .\n";
}
}
return 0;
}


Is at least a partial cleanup. Even better is you state tro break it out to functions....

ltcmelo
March 24th, 2007, 04:19 PM
Hi Xaro.

Eifficient in which way? Faster? Since this is a very simple program, you're probably beginning in C++. Perhaps, the first thing you might wanna try in your program is to rewrite it withoug using 'goto's. Usually, 'goto' is not a good practice from a software engineering point of view. For instance, in the case of your program you can achieve the same effect using a loop. Particularly, you could have something like this:


std::cin >> quit;
while (quit != "Quit")
{
std::cout << "You did not type quit!\n";

//...

std::cin >> quit;
}


A final observation is that you don't really need all those variables for the program.

Xaro
March 24th, 2007, 05:49 PM
Cheers, i didnt think of using:

while (quit != "Quit")


And yes, I am just a beginner.

:)

Xaro