Basic code from the website's Do-while tutorial. Basically you enter a number and the program tells you what you typed in, 0 terminates the function.
My question is, how could I alter it so that when 0 is typed, instead of displaying "you entered: 0," it would respond with something like "program terminated" I tried using a second do-while but it created an infinite loop. The code that follows is my second attempt. It's not looped anymore but it still doesn't remove the "You entered: 0" from the do-while. I'm not sure why. I should know this stuff, I got a B in C++ in high school but it's been a little while haha. Help and thanks!
----------
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
unsigned long n;
do {
cout << "Enter a number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
It would duplicate a bit of code, but you could ask for the user's input outside of the loop once, and then print what they entered before asking them for their next input. You could also place a check inside the loop that breaks if n == 0 instead of using it as the loop condition.
do
{
cout << "Enter a number (0 to end): ";
cin >> n;
if (n != 0)
cout << "You entered: " << n << "\n";
else
cout << "Program terminated\n";
} while (n != 0);
Add a condition if else inside the do while. Since the condition is evaluated only at the end in a do while you can run checks before the loop terminates as you see here.
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
int main ()
{
unsignedlong n;
do
{
cout << "Enter a number (0 to end): ";
cin >> n;
if (n == 0) //this allows you to have it checked inside the loop, exactly as zhuge said
{
cout << "Program terminated\n";
system("PAUSE");
return 0;
}
cout << "You entered: " << n << "\n";
} while (n != 0);
}
Awesome! Thanks for your help guys! I think wasn't considering putting the if statement in the loop because of the while condition. Didn't make a connection that i could break the loop. Dang I feel super rusty right now.