if else statement

Hey guys i'm looking through a program that my instructor has put online for us to use as an example but i'm having trouble understanding a small piece of it, could anyone explain to me what this if else statement is doing? thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
 #include<iostream>
using namespace std;
int main()
{
char newcard;
char newsuite;
string input;
cout<<"Enter the card notation: ";
cin>>input;
if(input.length()==3)
{newcard='X';
newsuite=input[2];
}
else
{newcard=input[0];
newsuite=input[1];
}
switch(newcard)	// Sets "if conditions" to the newcard char. Ex : if user inputs A, out put will be Ace.
{case 'A': cout<<"Ace "; break;
case '2': cout<<"2 "; break;
case '3': cout<<"3 "; break;	// break stops the program from continuing if its found the answer.
case '4': cout<<"4 "; break;
case '5': cout<<"5 "; break;
case '6': cout<<"6 "; break;
case '7': cout<<"7 "; break;
case '8': cout<<"8 "; break;
case '9': cout<<"9 "; break;
case 'J': cout<<"Jack "; break;
case 'Q': cout<<"Queen "; break;
case 'K': cout<<"King "; break;

}
switch(newsuite)	// Sets conditions just as the card number but with the newsuite of the card.
{case 'H': cout<<"of Hearts\n";break;
case 'D': cout<<"of Diamonds\n";break;
case 'C': cout<<"of Clubs\n";break;
case 'S': cout<<"of Spades\n";break;
}
return 0;
}



// im having trouble understanding the if else statement what is this statement doing???

if(input.length()==3)
{newcard='X';
newsuite=input[2];
}
else
{newcard=input[0];
newsuite=input[1];
Well. Say the user inputs "Hey" in the "input". So now string input = "Hey".

input.lenght = 3 bytes. Because there are 3 characters.
If string input = "Yellow" it would be equal to 6 bytes.

So the
1
2
3
4
f(input.length()==3)
{newcard='X';
newsuite=input[2];
}

Does this. If input.lenght == 3 (in this case it is, because the user entered "hey")

Then what it does is that, it assigns char newcard the character X. So now if you print out newcard you will get "x".
Then it assigns newsuite the third letter of string input, which is in this case the "y".

this -

1
2
3
4
5
else
{newcard=input[0];
newsuite=input[1];
}
 


this is triggered if input is more or less than 3 bytes.
So, if what the user inputs (say the example from before, the user inputs "Yellow")

Then it will assign newcard the first letter of that word. so newcard will be = 'Y'.
newsuite will be assigned the second letter of that word. so newsuit will be = 'o'.

Hope it helped.
Last edited on
Awesome, everything is clear now, thank you so much!
Glad I could help! :)
Topic archived. No new replies allowed.