C++ while statement, with nested if else - c++

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.

Related

Why are my or operators not working as intended?

My if statements are getting hit no matter the input. I can't wrap my head around why. Here is the code:
void Novice::selection()
{
char selection, shift;
cout << "Please select a section to run: A - Home Row, B - Bottom Row, C - Top Row, D - Pointer Fingers, E - Right Pinky;" << endl;
cin >> selection;
selection = toupper(selection);
if (selection != 'A' || 'B' || 'C' || 'D' || 'E') {
cout << "Invalid Input. Please select again" << endl;
cin >> selection;
}
if (selection == 'A' || 'B' || 'C') {
cout << "you're here" << endl;
}
If input is 'A', the first if statement triggers, if I then put in A again second if statement triggers as well. Any help would be appreciated.
This is not how logical operators work in c++. To compare against multiple values, you need to do:
if (selection == 'A' || selection == 'B' || selection == 'C') {
// ...
}
Note that your first if is incorrect, even if you use the fix above. If you check whether a value is not equal to several other values, this will always be true. That condition probably needs to be something like:
if (selection != 'A' && selection != 'B' &&
selection != 'C' && selection != 'D' && selection != 'E') {
// ...
}
Alternatively, for the first if condition, you can use a switch statement, like this:
switch ( selection )
{
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
break;
default:
cout << "Invalid Input. Please select again" << endl;
cin >> selection;
}

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;
}
}

Using the OR Operator with Strings in 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");
}
}

I can not find the error that causes my array to get corrupted after running the case twice and exiting

Hello everyone i am getting a Run-Time Check Failure #2 - Stack around the variable 'barray2' was corrupted. this happens when i loop twice or more the same case and right when i decide to break the while loop with a e for exit. here is the sample of my code. do i have to clear the array when ever i am done? i try and add a barray[16]={0}; inside the case after it prints but i get a expression error, i got no clue :(
#include<iostream>
#include<iomanip>
#include<array>
using namespace std;
int main()
{
int num(0),k(0);
int barray[16]={0};
int num2(0),k2(0);
int barray2[16]={0};
int choice(2);
int choice2;
char option;
while(choice != -1)
{
cout << "enter a choice from B, O, or e(exit)" <<endl;
cin >> option;
if (option == 'B' || option == 'b')
choice2 = 1;
else if (option == 'O' || option == 'o')
choice2 = 2;
else if (option == 'e')
choice2 = -1;
else
choice2 = 0;
switch(choice2)
{
case 1:
cout<<"please enter integer number to be converted to binary (lessthan 65536) "<<endl;
cin>>num;
while ((num !=0) && (k<=15))
{
barray[k]=num%2;
num=num/2;
k++;
}
for (k=15;k>=0;k--)
{
cout<<barray[k];
if ((k%4)==0)
cout<<" ";
}
cout<<endl;
break;
case 2:
cout<<"please enter integer number to be converted to octal (lessthan 65536) "<<endl;
cin>>num2;
while ((num2 !=0) && (k2<=15))
{
barray2[k2]= num2 % 8;
num2 = num2 / 8;
k2++;
}
for (k2=15; k2>=0; k2--)
{
cout<<barray2[k2];
if ((k2%4)==0)
cout<<" ";
}
cout<<endl;
break;
case -1:
cout << "you entered " << choice2 << endl;
choice = -1;
break;
default:
cout << "try again " << endl;
}
}
}
You do not re-initialize your counters k and k2.
The loops quoted below leave k and k2 set to -1 after they complete. So, on the second pass of your while loop, you write to one index before the array:
for (k=15;k>=0;k--)
{
}
for (k2=15; k2>=0; k2--)
{
//...
}
For clarity, I would initialize k/k2 explicitly before each while loop that uses it:
k = 0;
while ((num !=0) && (k<=15))
{
//...
}
(and likewise for the other loop with k2.)