How to make cin accept a single digit only c++ - c++

So we were challenged by a teacher to make this simple game into a c++ program.
English is not my primary language but I'll try to explain. I'm a beginner so these will not be efficient, but I'm still proud of what I did so far.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int secret[3], i = 0, x, y, z, a, b, c, guess = 1, tries = 9;
bool correct = false;
srand(time(0));
do
{
secret[i] = rand() % 10;
i++;
} while (i <= 2);
x = secret[0];
y = secret[1];
z = secret[2];
//cout << x << y << z << endl; <--- for debugging purposes
cout << "=================================================\n\n";
cout << " I HAVE THREE SINGLE DIGIT NUMBERS\n\n";
cout << " YOU HAVE TEN TRIES TO GUESS ALL THREE DIGITS\n\n";
cout << "=================================================\n\n";
do
{
cout << "\n\nGuess the first digit.\n";
while (!(cin >> a))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n";
}
cout << "\n\nGuess the second digit.\n";
cout << a;
while (!(cin >> b))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n" << a;
}
cout << "\n\nGuess the third digit.\n";
cout << a << b;
while (!(cin >> c))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n" << a << b;
}
cout << "\n\n====================================================\n\n";
if (tries == 0)
{
cout << "YOU RAN OUT OF GUESSES! \n";
cout << "The secret number is " << x << y << z << "!\n";
cout << "PLEASE RESTART THE PROGRAM TO TRY AGAIN!\n";
correct = true;
}
else if ((a == x) && (b == y) && (c == z))
{
cout << "YOU GUESSED THE SECRET NUMBER IN " << guess << " TRY / TRIES!\n";
cout << "CONGRATULATIONS!\n\n";
correct = true;
}
else if ((a == x) && (b == y) && (c != z))
{
cout << "You guessed TWO of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a == x) && (b != y) && (c != z))
{
cout << "You guessed ONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a == x) && (b != y) && (c == z))
{
cout << "You guessed TWO of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a != x) && (b == y) && (c == z))
{
cout << "You guessed TWO of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a != x) && (b == y) && (c != z))
{
cout << "You guessed ONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else if ((a != x) && (b != y) && (c == z))
{
cout << "You guessed ONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
else
{
cout << "You guessed NONE of the numbers correctly!\n";
cout << "You have " << tries << " tries left.\n";
correct = false;
}
cout << "\n====================================================\n\n";
guess++;
tries--;
} while (correct == false);
}
I have a little problem though, in this part of the program,
cout << "\n\nGuess the first digit.\n";
while (!(cin >> a))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Please try again: \n";
}
I could enter anything invalid and it will properly identify it as an invalid input. But if I enter 2 digits (22 for example), the program still enters 22 and it just accepts it.
I don't know exactly how that part of my program works, I just copy-pasted it. Is it possible to modify it, or my program to only accept a single digit, 0-9, and identify the input as invalid when two numbers are entered?
I know it's just a minor inconvenience and doesn't really break the program, but if I can make it better then it would be great. I just want it to be perfect, if possible.
I'm guessing if there's something like _getche for integers then it would be better?
Thanks in advance.

while (!(cin >> a)) means keep looping while not able to convert the input to an integer value in a - you can add extra conditions:
while (!(cin >> a) || a < 0 || a > 9)
In those latter cases, there's no need to .clear() and .ignore(...) but it won't do any harm.
In case it's new to you, || means logical-or, the equivalent logic to English such as: "a is less than 0 OR a is greater than 9".

Related

Creating a function to output a string when the input is negative or zero. First time doing user-defined functions

I am trying to create a user-define function in C++ to prevent an endless loop from inputting an incorrect input for a double variable and check if an input is negative or zero. If that's the case the function will go into a do-while loop to ask the user to try again until the value is no longer something other than a double, negative, or zero.
The function fix() is the the user-defined
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
string fix(double x)
{
string B_error = "B cannot be zero or negative. Please try again: ";
string H_error = "H cannot be zero or negative. Please try again: ";
string h_error = "b cannot be zero or negative. Please try again: ";
string b_error = "h cannot be zero or negative. Please try again: ";
string r_error = "r cannot be zero or negative. Please try again: ";
string y_error;
while (!(cin >> x))
{
if (cin.fail())
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
if (x == 'B')
{
y_error = B_error;
if (x <= 0)
{
do
{
return y_error;
cin >> x;
}
while (x <= 0);
}
}
return 0;
}
int main()
{
int selection;
double I, B, H, b, h, r, fix(double);
cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";
while (!(cin >> selection) || selection < 1 || selection > 3)
{
if (cin.fail() || selection < 1 || selection > 3)
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
switch (selection)
{
case 1:
cout << "You have selected I-beam. All inputs must be in inches.\n"
<< "Please input the value for B: ";
fix(B);
cout << "Please input the value for H: ";
fix(H);
if (H <= 0)
{
do
{
cout << "H cannot be zero or negative. Please try again: ";
cin >> H;
}
while (H <= 0);
}
cout << "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
else if (b > B)
{
do
{
cout << "b cannot be larger than B. Please try again: ";
cin >> b;
}
while (b > B);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
else if (h > H)
{
do
{
cout << "h cannot be larger than H. Please try again: ";
cin >> H;
}
while (h > H);
}
I = (B*H*H*H - b*h*h*h)/12.;
cout << "\nResults for an I-beam with B = " << B
<< ", H = " << H << ", b = " << b << ", and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 2:
cout << "You have selected rectangular beam. All inputs must be in inches.\n"
<< "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
I = b*h*h*h/12.;
cout << "\nResults for a rectangular beam with b = " << b << " and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 3:
cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
<< "Please input the value of r: ";
fix(r);
if (r <= 0)
{
do
{
cout << "r cannot be zero or negative. Please try again: ";
cin >> r;
}
while (r <= 0);
}
I = M_PI*pow(r,4)/4.;
cout << "\nResults for a cylindrical beam with r = " << r << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
}
cout << "The value of the moment of inertia for this beam is: " << I << "in^4" << "\n\n";
return 0;
}
I removed the issues. You are confusing instances of classes with functions. Functions don't have to be initialized, instances have to if they are outside of the class.
I wrote some comments along the code. It is still not beautiful but at least it works.
string FUNCTION(double) btw. means the function only can or should return a "string". If you are returning nothing the function is written like so void FUNCTION(double).
If your return f.e. a string you have to write something that is receiving the returned string like so:
#include <iostream>
/*
std::string returning_value;
returning_value = FUNCTION(1.0);
*/
//or
std::string FUNCTION(double function_a); //prototype of the function
//you need this if you write the function underneath the main() function
//The main function is returning "return 0" so since "0" is an "int"
//meaning main is always "int main()" btw. because it is a function,
//just not some function but the "main function" thats called by the OS
int main()
{
std::string returning_value;
double a = 0.1; //initializing with 0.1
returning_value = FUNCTION(a);
std::cout << returning_value << std::endl;
//and in both cases the function would look like:
return 0;
}
std::string FUNCTION(double function_a)
{
std::string returning_value_a = "This is a string that will be returned";
if(function_a == 0.1)
{
returning_value_a = "This is another string";
}
return returning_value_a;
}
Your code with the least amount fixed that you got it at least working
and you can test with how to get the right output you want to get. Have fun :) Hope my answer helps you :)
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
void fix(double x)
{
string B_error = "B cannot be zero or negative. Please try again: ";
string H_error = "H cannot be zero or negative. Please try again: ";
string h_error = "b cannot be zero or negative. Please try again: ";
string b_error = "h cannot be zero or negative. Please try again: ";
string r_error = "r cannot be zero or negative. Please try again: ";
string y_error;
while (!(cin >> x))
{
if (cin.fail())
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
//warning: comparing floating point with == or != is unsafe
if (x == 'B')
{
y_error = B_error;
if (x <= 0)
{
do
{
cin >> x;
}
while (x <= 0);
}
}
}
int main()
{
int selection;
double I, B, H, b, h, r;
//You need to initialize the variables with a value
I = 1.0;
B = 1.0;
H = 1.0;
b = 1.0;
h = 1.0;
r = 1.0;
//functions don't need to be initialized, thats for Instanzes of classes
//double fix(double);
cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";
while (!(cin >> selection) || selection < 1 || selection > 3)
{
if (cin.fail() || selection < 1 || selection > 3)
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
switch (selection)
{
case 1:
cout << "You have selected I-beam. All inputs must be in inches.\n"
<< "Please input the value for B: ";
fix(B);
cout << "Please input the value for H: ";
fix(H);
if (H <= 0)
{
do
{
cout << "H cannot be zero or negative. Please try again: ";
cin >> H;
}
while (H <= 0);
}
cout << "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
else if (b > B)
{
do
{
cout << "b cannot be larger than B. Please try again: ";
cin >> b;
}
while (b > B);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
else if (h > H)
{
do
{
cout << "h cannot be larger than H. Please try again: ";
cin >> H;
}
while (h > H);
}
I = (B*H*H*H - b*h*h*h)/12.;
cout << "\nResults for an I-beam with B = " << B
<< ", H = " << H << ", b = " << b << ", and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 2:
cout << "You have selected rectangular beam. All inputs must be in inches.\n"
<< "Please input the value for b: ";
fix(b);
if (b <= 0)
{
do
{
cout << "b cannot be zero or negative. Please try again: ";
cin >> b;
}
while (b <= 0);
}
cout << "Please input the value for h: ";
fix(h);
if (h <= 0)
{
do
{
cout << "h cannot be zero or negative. Please try again: ";
cin >> h;
}
while (h <= 0);
}
I = b*h*h*h/12.;
cout << "\nResults for a rectangular beam with b = " << b << " and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 3:
cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
<< "Please input the value of r: ";
fix(r);
if (r <= 0)
{
do
{
cout << "r cannot be zero or negative. Please try again: ";
cin >> r;
}
while (r <= 0);
}
I = M_PI*pow(r,4)/4.;
cout << "\nResults for a cylindrical beam with r = " << r << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
}
cout << "The value of the moment of inertia for this beam is: " << I << "in^4" << "\n\n";
return 0;
}
So, I had to add another function to check if B < b and H < h and add a do-while loop after the while loop in the fix function.
Here's my code with the fix:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
void fix(double &x)
{
while (!(cin >> x))
{
if (cin.fail())
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not a double
cin.ignore(10000, '\n');
}
}
string return_x = "This cannot be zero or negative. Please try again: ";
while (x <= 0)
{
cout << return_x << endl;
cin >> x;
}
}
void fix2(double &x, double &y)
{
while (x < y)
{
cout << x << " cannot be less than " << y << endl;
fix(y);
}
}
int main()
{
int selection;
double I = 1.0;
double B = 1.0;
double H = 1.0;
double b = 1.0;
double h = 1.0;
double r = 1.0;
cout << "Please select the type of beam:\n"
<< "1) I-Beam\n"
<< "2) Rectangular Beam\n"
<< "3) Cylindrical Beam\n";
while (!(cin >> selection) || selection < 1 || selection > 3)
{
if (cin.fail() || selection < 1 || selection > 3)
{
cout << "Erroneous input. Please try again:\n";
cin.clear(); // used to prevent an endless loop if an input type is not an integer
cin.ignore(10000, '\n');
}
}
switch (selection)
{
case 1:
cout << "You have selected I-beam. All inputs must be in inches.\n"
<< "Please input the value for B: ";
fix(B);
cout << "Please input the value for H: ";
fix(H);
cout << "Please input the value for b: ";
fix(b);
fix2(B, b);
cout << "Please input the value for h: ";
fix(h);
fix2(H, h);
I = (B * H * H * H - b * h * h * h) / 12.;
cout << "\nResults for an I-beam with B = " << B << ", H = " << H
<< ", b = " << b << ", and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 2:
cout << "You have selected rectangular beam. All inputs must be in inches.\n"
<< "Please input the value for b: ";
fix(b);
cout << "Please input the value for h: ";
fix(h);
I = b * h * h * h / 12.;
cout << "\nResults for a rectangular beam with b = " << b
<< " and h = " << h << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
case 3:
cout << "You have selected cylindrical beam. All inputs must be in inches.\n"
<< "Please input the value of r: ";
fix(r);
I = M_PI * pow(r, 4) / 4.;
cout << "\nResults for a cylindrical beam with r = " << r << endl;
cout << setfill('-') << setw(32) << "" << endl;
break;
}
cout << "The value of the moment of inertia for this beam is: " << I
<< "in^4" << "\n\n";
return 0;
}

Can't figure out how to give user all the options for starting, stopping, and restarting program?

Ok so I am trying to build this random number teller which basically tells the users whether the number they input is less than, greater than, or equal to 50 and also give them the options to start, stop, and restart the "random number teller" Here is the code:
#include <iostream>
using namespace std;
main() {
cin >> boolalpha;
int invalid_answer {0};
const int const_num {50};
int random_num {};
char answer {};
int keep_going {};
while (keep_going == 0) {
while (invalid_answer == 0) {
//=======================================================================================================================================
cout << "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " << endl;
cin >> random_num;
if (random_num > const_num) {
cout << random_num << " is greater than " << const_num;
}
else if (random_num == const_num) {
cout << random_num << " is the same as " << const_num << endl;
}
else {
cout << random_num << " is less than " << const_num << endl;
}
cout << "Want to try again? Type \"Y\" or \"N\"";
cin >> answer;
//=======================================================================================================================================
if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}
//=======================================================================================================================================
while(answer == 'Y') {
cout << "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " << endl;
cin >> random_num;
if (random_num > const_num) {
cout << random_num << " is greater than " << const_num;
}
else if (random_num == const_num) {
cout << random_num << " is the same as " << const_num << endl;
}
else {
cout << random_num << " is less than " << const_num << endl;
}
cout << "\nWant to try again? Type \"Y\" or \"N\"";
cin >> answer;
}
//=======================================================================================================================================
if (answer != 'Y' || answer != 'N') {
invalid_answer = 1;
}
//=======================================================================================================================================
while (invalid_answer == 1) {
cout << "I'm sorry what? Please note that answers are case sensitive. Answer again: ";
cin >> answer;
if (answer == 'Y') {
invalid_answer = 0;
}
else if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}
}
}
}
}
Whenever I say "N" for No I don't want to redo the random number checker, it doesn't change keep_going to 1 it just moves on to one of the other if or while statements below it. So when you input "N" it just outputs either "Enter a random number and we will tell you if it is greater than or less than " << const_num << ": " or "I'm sorry what? Please note that answers are case sensitive. Answer again: "
The problem is with this bit of code:
if (answer != 'Y' || answer != 'N') {
invalid_answer = 1;
}
When answer is 'N', answer != 'Y' is true and invalid_answer is set to 1 (because of short-circuit evaluation the rhs of the logical OR is not even evaluated - see quote below).
So the execution will enter the while
while (invalid_answer == 1)
and will print the statements.
You can correct this by:
if (answer == 'Y' || answer == 'N') { //if input is either 'Y' or 'N'
invalid_answer = 0;
}
else { //for all other inputs
invalid_answer = 1;
}
Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first), but overloaded operators behave like regular function calls and always evaluate both operands
Also note that main should have the type int.
I figured it out right after I posted the question haha, basically the answer above was correct so I had to split that if statement into 2 others, in which I added an else statement to each also that said invalid_answer = 0; to make sure. But then after the user's second time using the program, if they wanted to quit it wouldn't let them and would just restart it again. I solved that by adding
if (answer == 'N') {
cout << "Ok then, sorry to see you miss out" << endl;
keep_going = 1;
}`
to the bottom of the while(answer == 'Y') loop.

How to end my while loop? [duplicate]

This question already has answers here:
Immediate exit of 'while' loop in C++ [closed]
(10 answers)
Closed 6 years ago.
Hey can anyone lend me a hand? How can I make my loop end after the first calculation? After i complete one calculation such as addition, I would like to end it. Sorry for the noobie questions. I'm just learning loops now in my class. Greatly appreciated.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int numOne;
int numTwo;
int result;
string operation;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
while (operation == "e" || operation == "E")
{
cout << "Operation type invalid." << endl;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
}
while (operation == "+" || operation == "-" || operation == "*" || operation == "/")
{
cout << "Please enter integer one: ";
cin >> numOne;
cout << "Please enter integer two: ";
cin >> numTwo;
if (operation == "+")
{
result = numOne + numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << "." << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
else if (operation == "-")
{
result = numOne - numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << "." << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
else if (operation == "*")
{
result = numOne * numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
else if (operation == "/")
{
if (numTwo == 0)
{
cout << "You cannot divide by zero!" << endl;
}
else
{
result = numOne / numTwo;
cout << "The numbers you entered were " << numOne << "," << numTwo << endl;
cout << "The operation you chose was " << operation << "." << endl;
cout << "The operations result is " << result << endl;
cout << "Your equation was: " << numOne << " " << operation << " " << numTwo << " = " << result << ".";
}
}
}
return 0;
}
I'm not allowed to use break. Is there another way?
You can end a while loop using...
break;
ie
if(!(operation == "e" || operation == "E")) {
break;
}
Normally to end a while loop the (EXPRESSION) in the following ie
while((EXPRESSION) == true) { execute_code_here();}
needs to evaluate to false. The expression can be made up of many logical pieces ie
while (a == b && c != d && f++ < 1000) {do_something_here();}
The break keyword is used to terminate a while loop early but this can also be achieved by adding something to the expression that allows you to terminate the while loop ie make the expression evaluate to false, this is normally done using a flag or a counter.
To achieve the same effect as break without using it you can use this technique with continue. You then use the flag or counter along with continue to achieve the same thing as break ie, this is a counter example
while(a == b && flag++ < 1000) {
if(this_returns_true()) {
flag = 10000;
continue;
}
/*The code here may not be executed*/
}
Using a boolean flag it would be...
while(a == b && flag == true) {
if(this_returns_true()) {
flag = false;
continue;
}
/*The code here may not be executed*/
}
Just change the while to if. There's no need for a loop if you only want to execute something once.
You can use break; with an if statement inside the while loop. So that if a condition is true you will break out from the while loop.
Example
if (operation != "e")
break;
If you're not allowed to use break, I suggest you don't use a loop. And just calculate it once.
I am not very experienced with C++ but I think you mean the break; statement
https://msdn.microsoft.com/library/37zc9d2w.aspx
Use
break;
This will end the loop each time. You can wrap an if statement around it to apply conditions for exiting.
If you have to use the while loop just add break; and that will break out of the loop. If you don't have to I would change that to an if statement. Example: if(varName == '+'){
Num1 + num2;}
Sorry for format, on mobile
The code block:
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
while (operation == "e" || operation == "E")
{
cout << "Operation type invalid." << endl;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
}
Doesn't do what you're promising the user:
Please enter what operation you'd like to perform or e/E to end program:
If "e" or "E" is entered, the loop won't stop and ask for input again.
You probably want to have something like this:
do {
cin >> operation;
while (operation == "+" || operation == "-" || operation == "*" || operation == "/") {
// ...
}
} while(operation != "e" && operation != "E");
As for your silly restrictions not to use do {} while(); (kick your professor in the ass, do twice at least):
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
while(operation != "e" && operation != "E") {
if (operation == "+" || operation == "-" || operation == "*" || operation == "/") {
// ...
}
else {
cout << "Operation type invalid." << endl;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
}
}
I guess that what you are actually trying to achieve is this.
The first loop should be refactored (ie: loop until operation is nether 'e' nor 'E'), the second loop should be an if-else-statement (checking whether the operation is valid).
int main()
{
int numOne;
int numTwo;
int result;
string operation;
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
while (operation != "e" && operation != "E") {
if (operation == "+" || operation == "-" || operation == "*" || operation == "/") {
// your valid operation code...
} else {
cout << "Operation type invalid." << endl;
}
cout << "Please enter what operation you'd like to perform or e/E to end program: ";
cin >> operation;
}
return 0;
}

How do I loop back to the beginning in c++

I recently started programming in C++, so for my program I need to loop back to the beginning when the user says yes and end the program when the user says no. I was wondering how would I loop back to the beginning?
#include <iostream>
using namespace std;
int main() {
int x;
int y;
char yes, no, answer;
{
cout << "Please enter a number for the x coordinate" << endl;
cin >> x;
cout << "Please enter a number for the y coordinate" << endl;
cin >> y;
if (x == 0) {
if (y == 0)
cout << "you are on the origin" << endl;
else
cout << "you are on the y axis" << endl;
}
else if (x > 0) {
if (y == 0)
cout << "you are on the x coordinate" << endl;
else if (y > 0)
cout << "you are in the 1st quadrant" << endl;
else
cout << "you are in the 4th qaudrant" << endl;
}
else if (x < 0) {
if (y > 0)
cout << "you are in the 2nd quadrant" << endl;
else if (y < 0)
cout << "you are in the 3rd quadrant" << endl;
}
cout << "Do you want to run the program again either types yes or no" << endl;
cin >> answer;
if (answer == 'yes' || answer == 'Yes')
system("pause");
}
}
You can put the code inside a loop:
while(true) {
... (existing code goes here)
if (answer != 'yes' && answer != 'Yes')
break;
}

Why does my OR conditions to check string for matches always return true

I'm writing the classic "Guess my number" program.
I don't seem to understand why the while loop doesn't stop working even after I wrote "Success" and goes to the default route.
int xRan;
void rdm(int to, int from){
srand(time(NULL));
xRan = rand()%to+from;
}
void iGuess(){
string b;
int tries = 1;
cout << "Think of a number between 1 and 100" << endl;
rdm(100, 1);
while(b != "Success" || b != "success"){
cout << "is your number higher or lower than " << xRan << ". (attempt #" << tries << ")" << endl;
cout << "If I guessed your number, please type 'Success' " << endl;
cout << "-->";
cin >> b;
if(b == "Lower" || b == "lower"){
rdm(xRan, 1);
tries++;
}else if(b == "Higher" || b == "higher"){
rdm(100, xRan);
tries++;
}else{
cout << "This is not a valid choice." << endl;
}
}
cout << "I'm so good! I did it in " << tries << "attempts!" << endl;
}
You never leave your for loop because you are checking if it is "Success" or "success". Either one can be true and go into the loop. So whether you type it with capitals or not one of those will be true. Instead write
while(b != "Success" && b != "success")