Using the OR Operator with Strings in C++ - c++

To start, I'm trying to make a GPA calculator for my class.
I know how to compare strings, so I'm good there. The issue I'm having is that I'm trying to set up a situation so when the user inputs anything other than a letter grade value, it will return an error message. I've set up two arrays, one that stores string values and another that stores integral values. The idea was to use the string array to store the entered grade letter inputs, then use those to determine the GPA value for each class. It would then store that value into the integral array. I hate to be obnoxious, but here's the code for the first section alone:
void gpaCalSetClassNum5(){
string mathWeight5;
string scienceWeight5;
string historyWeight5;
string englishWeight5;
string elective1Weight5;
string elective2Weight5;
string gpaClassSet5[] = {"null", "null", "null", "null", "null"};
int gpaClassSet5int[] = {};
cout << "Enter the grade value of each of your classes." << endl;
/////////////////////////
MATH:
cout << "Math" << endl;
cin >> gpaClassSet5[0];
if (gpaClassSet5[0] == "A") {
gpaClassSet5int[0] = 4;
} else if (gpaClassSet5[0] == "a") {
gpaClassSet5int[0] = 4;
} else if (gpaClassSet5[0] == "B") {
gpaClassSet5int[0] = 3;
} else if (gpaClassSet5[0] == "b") {
gpaClassSet5int[0] = 3;
} else if (gpaClassSet5[0] == "C") {
gpaClassSet5int[0] = 2;
} else if (gpaClassSet5[0] == "c") {
gpaClassSet5int[0] = 2;
} else if (gpaClassSet5[0] == "D") {
gpaClassSet5int[0] = 1;
} else if (gpaClassSet5[0] == "d") {
gpaClassSet5int[0] = 1;
} else if (gpaClassSet5[0] == "F") {
gpaClassSet5int[0] = 0;
} else if (gpaClassSet5[0] == "f") {
gpaClassSet5int[0] = 0;
} else if (gpaClassSet5[0] != ){
cout << "Did you enter a letter grade value?" << endl;
goto MATH;
}
cout << "You have selected " << gpaClassSet5[0] << ", or " << gpaClassSet5int[0] << endl;
cout << "Is this class weighted? Use Y/N." << endl;
cin >> mathWeight5;
if (mathWeight5 == "Y" || "y") {
gpaClassSet5int[0] = gpaClassSet5int[0] + 1;
}
I'm looking for a simplified version of this. Why can't I use something like:
if(gpaClassSet5[0] == "A" || "a"){
//stuff//
}
I'm in need of a simplified version because, like a switch, I'd like to use different inputs to do different things -- but ultimately have a default in case any of the values listed weren't entered.
How can I do this? How can I set up a switch in C++?
Sorry if this question is a little dumb, I'm getting into C++ and these self-made programs are really my only practice.
Full program code here: http://justpaste.it/ee4u

Because that's not how C++ is specified to work, you need to do the comparison twice:
if(gpaClassSet5[0] == "A" || gpaClassSet5[0] == "a")
The logical OR operation means "if the left-hand expression is true, or the right-hand expression is true". In your case with the code as in your question, the right-hand side expression will always be true as "a" is not zero (i.e. false).

Operator precedence says you can't do it this way. gpaClassSet5[0] == "A" || "a" is the same as (gpaClassSet5[0] == "A") || ("a").
If you don't want to write gpaClassSet5[0] twice, you could use regular expressions if you don't mind a performance hit
std::regex_match(gpaClassSet5[0], std::regex("A|a"));
This gets more sensible if you test against a lot of possible matches:
std::regex_match(gpaClassSet5[0], std::regex("A|Grade A|1|Excellent|Outstanding|Perfect|Perfect Score)"));
If you are not using C++11 (don't have std::regex), you can use boost::regex from boost.org.
Or you could solve your specific code example with more compact logic:
char gradeLetter = std::tolower(gpaClassSet5[0])
if (gradeLetter >= 'a' && gradeLetter <= 'd')
gpaClassSet5int[0] = 4-(gradeLetter -'a');
else if (gradeLetter == 'f')
gpaClassSet5int[0] = 0;
else
{
cout << "Did you enter a letter grade value?" << endl;
goto MATH;
}
And extract a function to get rid of the goto and make the code easier to read:
int ConvertLetterToNumericGrade(char gradeLetter)
{
char lower = std::tolower(gradeLetter);
if (lower >= 'a' && lower <= 'd')
return 4-(lower -'a');
if (lower == 'f')
return 0;
throw std::runtime_error("cannot convert invalid grade letter");
}
void gpaCalSetClassNum5()
{
...
while (true)
{
cin >> gpaClassSet5[0];
try { gpaClassSet5int[0] = ConvertLetterToNumericGrade(gpaClassSet5[0]); }
catch (const std::runtime_error& )
{
cout << "Did you enter a letter grade value?" << endl;
continue;
}
break;
}
...
}
And with a switch (which is not supported for strings, but is supported for char and wchar):
int ConvertLetterToNumericGrade(char gradeLetter)
{
switch (gradeLetter)
{
case 'a':
case 'A':
return 4;
case 'b':
case 'B':
return 3;
case 'c':
case 'C':
return 2;
case 'd':
case 'D':
return 1;
case 'f':
case 'F':
return 0;
default:
cout << "Did you enter a letter grade value?" << endl;
throw std::runtime_error("cannot convert invalid grade letter");
}
}
Resp.
int ConvertLetterToNumericGrade(char gradeLetter)
{
switch (std::tolower(gradeLetter))
{
case 'a': return 4;
case 'b': return 3;
case 'c': return 2;
case 'd': return 1;
case 'f': return 0;
default:
cout << "Did you enter a letter grade value?" << endl;
throw std::runtime_error("cannot convert invalid grade letter");
}
}

Related

If statements in for loops

how do I run only one of those if statements in a for loop? For example i have an input of 5...and i just want it to print five...but whenever i run this code, it will execute all if statement..please help me
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
// Complete the code.
int a;
int b;
cin >> a;
for (a = 0; 0<a<10; a++)
{
if (a == 1)
{
cout << "one";
}
if (a == 2)
{
cout << "two";
}
if (a == 3)
{
cout << "three";
}
if (a == 4)
{
cout << "four";
}
if (a == 5)
{
cout << "five";
}
if (a == 6)
{
cout << "six";
}
if (a == 7)
{
cout << "seven";
}
if (a == 8)
{
cout << "eight";
}
if (a == 9)
{
cout << "nine";
}
else if (a > 9 && a%2 == 0)
{
cout << "even";
}
else if (a > 9 && a&2 != 0)
{
cout << "odd";
}
}
return 0;
}
The problem seems to be the for loop. Your program accepts a value for a as an input, but then as soon as the loop begins, it resets the value of a to 0 (for (a = 0;...
Therefore it's looping 10 times, and on each loop a will have a different value, starting from 0 and ending at 9. This means that all of your if statements will get hit at some point in the execution, generally one on each of the loops round the for.
To get your expected behaviour " input of 5...and i just want it to print five", simply remove the for loop from your code.
Your unnecessary for loop trashes the input value of a and loops forever! (At least until you overflow your signed type a).
You are replacing a by using it as the counter in the for loop! If you only ever want one output, then drop the for loop completely. If your for loop were to remain then your expression 0 < a < 10 ought to be recast as 0 < a && a < 10 : formally 0 < a < 10 is evaluated as (0 < a) < 10 which is either true < 10 or false < 10 which is always true.
Also consider refactoring your if else to set up explicitly mutually exclusive statements:
if (a == 1){
cout << "one";
} else if (a == 2){
cout << "two";
/*and so on*/
} else {
/*all other cases*/
}
Although in this case you might want to consider a switch block:
switch (a){
case 1:
cout << "one";
break; // to stop program control flowing into the next case
case 2:
cout << "two";
break;
/*and so on*/
default:
/*all other cases*/
}
if () {
} else if () {
}
Although,
switch() {
}
will be more efficient in your case.
Update 1
#Aleph0
Below is the solution
int main() {
int a;
cin >> a;
switch (a) {
case 1: cout << "one"; break;
case 2: cout << "two"; break;
case 3: cout << "three"; break;
case 4: cout << "four"; break;
case 5: cout << "five"; break;
case 6: cout << "six"; break;
case 7: cout << "seven"; break;
case 8: cout << "eight"; break;
case 9: cout << "nine"; break;
default: cout << ((a & (1 << 31)) ? "negative" : (a & 1) ? "odd" : "even"); break;
}
}
Question has been asked to do following
i have an input of 5...and i just want it to print five
And, someone has correctly mentioned above, for loop is immaterial here.

C++ while statement, with nested if else

I have been having an issue getting the if else statement to properly work in the code.
I have everything else where I need it, just we are supposed to have multiple entries input and it just automatically uses the responses and the else statements do not work.
int main ()
{
string dep = "Deposit";
string with = "Withdrawl";
string bal = "Balance";
char choice;
cout << "PLease enter options A, B, C, or Q to quit.\n";
cin >> choice;
switch (choice) //to make them all the same, same as using toUpper
{
case 'a':
case 'A':
cout << "";
break;
case 'b':
case 'B':
cout << "";
break;
case 'q':
case 'Q':
cout << "";
break;
}
int count = 1;
while (count <= 4)
{
if (choice == 'a' || 'A' )
cout << dep << endl;
else if (choice == 'b' || 'B' )
cout << with << endl;
else if(choice == 'c' || 'C' )
cout << bal << endl;
else
(choice !='a' && choice !='b' && choice !='c');
cout << "that is invalid, PLease enter options A, B, C, or Q to quit.\n";
++count ;
}
system ("PAUSE");
return 0;
}
You need to fix the conditional statements like this:
if (choice == 'a' || choice == 'A' )
What you have will always result in the first conditional being met because 'A' is equal to decimal 65.
if(choice == 'a'||'A'),the computers will run the 'a'||'A' first,and it's return 1 (in bool) ,and then run the
choice == 1,according to your codes, there are no choice == 1,so the codes in if will not be run.

Why does my if-else statements drip over towards the third else?

I'm trying to get an idea of how this control syntax works.
Note: this is part of my int.main function:
while(cin >> Options){
if(Options == 1){ //If I enter '1' here it will output: "aHi.Else."
cout << "a";
}else{
cout << "hi";
}
if(Options == 2){ //If I enter '2' here it will output: "hiaElse."
cout << "a";
}else{
cout <<"Hi.";
}
if(Options == 3){ //If I enter '3' here it will output: "hiHi.a"
cout << "a";
}else{
cout << "Else." << endl;
}
}
Why is it dripping over to else's and stuff? What's wrong with the syntax? I'm confused?
How am I supposed to use multiple if statements without else's included? Can you give an example?
The ifs are not dependent on each other, so if Options is anything but 1, it will execute the else branch of the first if statement, even if Options is 2 or 3. The same applies to the other ifs. Since Options can only be 1 or 2 or 3 (or something else), you will always get the else output for the other ifs.
You can chain else and if if you want to link multiple conditions to each other. In the example below, the last else only executes if Options is neither 1, nor 2, nor 3.
while(cin >> Options){
if(Options == 1){
cout << "a";
}
else if(Options == 2){
cout << "b";
}
else if(Options == 3){
cout << "c";
}
else{
cout << "Hello";
}
}
or using a switch statement:
while(cin >> Options){
switch(Options){
case 1:
cout << "a";
break;
case 2:
cout << "b";
break;
case 3:
cout << "c";
break;
default:
cout << "Hello";
}
}

How do I loop a statement in c++

I want to loop a question and make it say "press Y to continue or N to quit" but I don't quite know how. I tried to do a while loop but they haven't worked well. Here's the code:
cout << "press Y to play again or anything else to close: ";
cin >> val;
if (val != "Y" && val != "y")
{
spelaIgen = false;
}
}
Best for you to use cases to make your selections of "Y or N". The attempt you were making would have made it so any character other than Y would quit.
bool correctVal = false;
char val;
while (!correctVal)
{
cout << "press Y to play again or N to close: ";
cin >> val;
switch(val)
{
case 'y':
case 'Y':
spelaIgen = false;
correctVal = true;
break;
case 'n':
case 'N':
spelaIgen = true;
correctVal = true;
break;
default:
cout << "\nInvalid entry!" << endl;
}
}
You could do something like this. Initialize your input variable, then use that variable as your while condition. Continue iterating your while loop until they enter something other than 'y' or 'Y'.
char val = 'Y';
while (val == 'Y' || val == 'y')
{
// Do stuff
cout << "press Y to play again or anything else to close: ";
cin >> val;
}
I am assuming you are using the standard namespace in C++ here. Try the following:
string val = "Y";
while (val == "Y")
{
cout << "press Y to play again or anything else to close: ";
cin >> val;
if (val != "J" && val != "j")
{
spelaIgen = false;
}
}

how to change the switch-case statement to if-else statement

int number;
cin>>number;
switch (number)
{
case 1:
cout<<"My Favourite Subject is";
break;
case 2:
cout<<"Fundamentals of Programming";
break;
case 3:
cout<<"Exit";
break;
default:
cout<<"Invalid Data";
}
You replace switch statement with if-else
if (number == 1)
{
}
else if (number == 2)
{
}
...
{
}
else
{
// default here
}
//Hey this is fun!
int number;
cin>>number;
// ultra const!
static const char const * const table[] =
{
"Invalid Data",
"My Favourite Subject is",
"Fundamentals of Programming",
"Exit"
};
cout<<table[number&3];
//Who needs if statements!!?
Check whether number is equal to the first value from switch, if equal then output text, otherwise(else) check next number.
if ( number == /*put here value to check*/ )
// print some text
else
// do something else
This is my favorite, even though it is not what you asked for:
string res =
number==1 ? "My Favourite Subject is" :
number==2 ? "Fundamentals of Programming" :
number==3 ? "Exit" :
number==4 ? "Invalid Data" :
"";
cout<<res;
The good side here is that you don't have to constrain yourself to integer comparison. Instead of number==1 you can use any kind of complexComparisonReturningBoolean(number).
Also just for fun:
Just use capital letters and semi-colon instead of colon. Ah, and don't forget to add an evil macro :)
#define SWITCH(s) for(int switch_=s, b=1;b;b=0) {
#define CASE(n) } if ( switch_ == n ) {
#define DEFAULT }
int number;
cin>>number;
SWITCH(number)
{
CASE(1);
cout << "My Favourite Subject is";
break;
CASE(2);
cout << "Fundamentals of Programming";
break;
CASE(3);
cout << "Exit";
break;
DEFAULT;
cout << "Invalid Data";
}
This kill the 'switch' and if 'for' loop are not allowed, it is also possible to use a BREAK macro, but it is even more evil.
Replace the case statement with an if statement:
if (number == 1) {
cout<<"My Favourite Subject is";
} else if (number == 2) {
cout<<"Fundamentals of Programming";
} else if (number == 3) {
cout<<"Exit";
} else {
cout<<"Invalid Data";
}
if (number == 1) {
cout << "blah1";
}
else if (number == 2) {
cout << "blah2";
}
else if (number == 3) {
cout << "blah3";
}
else {
cout << "default";
}
Try :
if (number < 1 || number > 3) {
//
} else if (number == 1) {
//
} else if (number/2 == 1) {
//
} else if ((number - 1)/ 2 == 1) {
//
}
This helps you get more math expertise than just checking for equality.