I am below 18 and I learn c++ with myself , I need some help on basic programming of c++ . Thanks . Question is the second line . I get this code from a book and I have solve the other question except this .
/*
*Revise the program so that it keeps playing the game until the user wants to quit.(Question ^^)
*(Hint : Add another loop around the existing loop)
*
*/
#include <iostream>
using namespace std ;
int main()
{
int total = 0 , n = 0;
cout << "welcome to NIM .Pick a starting point ."<<endl;
cin >> total ;
while(total <= 0){
cout << "Starting point must be bigger than 0 "<<endl;
cout <<"Re-enter : ";
cin >> total ;
}
while (true)
{
if ((total % 3) == 2){
total = total - 2;
cout << "I am substracting 2 ."
}else{
total -- ;
cout << "I am substracting 1 ."
}
cout << "New total is " << total <<endl;
if (total <= 0 ){
cout << "I win " <<endl;
break;
}
cout <<"Enter a num to substract (1 or 2) : "
cin >> n;
while ( n < 1 || n > 2) {
cout <<"Input must be 1 or 2 ."<<endl;
cout << "Re-enter : ";
cin >> n ;
}
total = total - n;
cout << "New total is "<< total <<endl;
if (total <= 0){
cout << "You win !" <<endl;
break;
}
The program must keep restarting until unless the user says otherwise.
Example:
I want to keep displaying a certain message until the user has entered -99.
#include <iostream>
usingnamespace std ;
int main()
{
int total = 0 , n = 0 ;
char c ;
cout << "Welcome to NIM "<<endl;
cout << "Enter any letter to continue or enter 'q' or 'Q' to quit ." <<endl;
cin >> c;
while( c != 'q' || c != 'Q')
{
cout << "Pick a starting point ."<<endl;
cin >> total ;
while(total <= 0){
cout << "Starting point must be bigger than 0 "<<endl;
cout <<"Re-enter : ";
cin >> total ;
}
while (true)
{
if ((total % 3) == 2){
total = total - 2;
cout << "I am substracting 2 .";
}else{
total -- ;
cout << "I am substracting 1 .";
}
cout << "New total is " << total <<endl;
if (total <= 0 ){
cout << "I win " <<endl;
break;
}
cout <<"Enter a num to substract (1 or 2) : ";
cin >> n;
while ( n < 1 || n > 2) {
cout <<"Input must be 1 or 2 ."<<endl;
cout << "Re-enter : ";
cin >> n ;
}
total = total - n;
cout << "New total is "<< total <<endl;
if (total <= 0){
cout << "You win !" <<endl;
break;
}
}
cout << "Enter 'q' or 'Q' to quit or press others letters to continue."<<endl;
cin >> c;
}
return 0;
}
Line 13: You want &&, not ||. If c is 'q', then c!='Q' will be true causing you to execute the loop.
PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post. http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.