For some reason, logical statement in the while loop will not change the bool value when I type in "Y" or "N". It just remains 1, or true, no matter what.
#include <iostream>
#include <string>
usingnamespace std;
int main(){
// Declare variables and set some
double GPA = 0;
int CourseCount = 0;
string CourseName = "Test";
char Question;
bool Choice;
while (Choice = true) {
// Ask for the Course name and store it for later use
cout << "Please enter the course name: ";
cin >> CourseName;
cout << "Would you like to enter grades again?: ";
cin >> Question;
// Standardize the casing for this
toupper(Question);
if (Question = 'Y'){
Choice = true;
}
elseif (Question = 'N' ){
Choice = !true;
}
else {
cout << "\nERROR: Please enter a choice of Y/N.\n";
}
}
return 0;
}
This Choice = true is an assignment. The variable Choice is set first, and then the value of Choice (true) is used in the conditional.
This Choice == true is a relational operator that returns true, if the value of Choice is equal to true.
PS. It is good practice to write true == Choice. If you accidentally forget the second equal sign, then the compiler will stop on impossible assignment.
#include <iostream>
#include <string>
usingnamespace std;
int main(){
// Declare variables and set some
double GPA = 0;
int CourseCount = 0;
string CourseName = "Test";
char Question;
bool Choice = true;
while (Choice == true) {
// Ask for the Course name and store it for later use
cout << "Please enter the course name: ";
cin >> CourseName;
cout << "Would you like to enter grades again?: ";
cin >> Question;
// Standardize the casing for this
toupper(Question);
if (Question = 'Y'){
Choice = true;
}
elseif (Question = 'N' ){
Choice = !true;
}
else {
cout << "\nERROR: Please enter a choice of Y/N.\n";
}
}
return 0;
}
This still keeps looping through as if I never typed "n"
Just watch out for "=" and "==" :) For the beginners it may be hard to remember. If you want to make sure you won't make a mistake, you can do this trick(although, it does not always work):
What's the difference, you may ask? Well, let's suppose, that you did what you just did:
1 2 3 4 5 6
//Your version:
if(question = 'Y') // Bug! You are assigning, where you wanted to compare; but your compiler won't tell you that
//It's a bug that may be tricky.
//Safer version:
if('Y' = question) // Compilation error! You are assigning a value to a constant, which isn't legal.
In the second example, your compiler will show error, and you will notice your mistake.
#include <iostream>
#include <string>
usingnamespace std;
int main(){
// Declare variables and set some
double GPA = 0;
int CourseCount = 0;
string CourseName = "Test";
char Question;
bool Choice = true;
do{
// Ask for the Course name and store it for later use
cout << "Please enter the course name: ";
cin >> CourseName;
cout << "Would you like to enter grades again? Y/N: ";
cin >> Question;
}while(toupper(Question)=='Y');
}
return 0;
}