C++ - Using specific character input for 'if' statements - c++

I am, for lack of a better word, an absolute programming novice. And as it stands, I've been flung head first into programming something in two or three languages.
As part of an assignment, we have been tasked with essentially recreating a heads/tails flip, in the form of a random chance game.
The way it works is the player has ten credits to start off with. They are asked to input a wager, and then they are asked heads or tails. Picking either heads or tails sets off a number generator, and depending on the value, they may well end up winning or losing their wager.
I coded a similar version of this using HTML/CSS/JS, and it works. I'll leave a puush link to the file so you can view it yourselves to get an idea of what I'm trying to do: http://puu.sh/bP2V7/2ef63f4a1c.html
I'm trying to do, functionally, the same thing in C++ in the form of a command application. I know the code I'm using works fine, and it compiles without much of a hitch. It's a bit annoying that it closes down rather than resetting to a previous line, but that's a hurdle I'll jump over when I get to it.
I had a look around, and to be honest, whilst a few of the things may well work, I'm admittedly relatively clueless and some of the programmer speak kinda flies over my head.
It's probably because I'm being thrown into it and I'm not used to it yet, but as it stands, I need your help.
My code simply works as follows (simplified to save time):
int main()
{
int points, wager;
points = 10;
output "HEADS OR TAILS?";
if (player has 1 point or more)
{
output "Input wager";
input wager value;
output "Wager is (player input)";
output "Heads or Tails?";
input h or t; //This was what I wanted
if (player selects 'heads') //For sake of simplicity, the code
{ //here will account for both heads
int heads; //and tails.
srand(NULL);
heads = random number 1 and 2;
if (heads = 1)
{
output "HEADS!";
output "You win 'wager'!";
points = points + wager;
}
if (heads = 2)
{
output "TAILS!";
output "You lose 'wager'!";
points = points - wager;
}
}
}
if (player has 0 points)
{
output "GAME OVER";
}
}
What I want to do is have the user input either an 'h' or a 't' to determine whether or not they want heads or tails.

In your programming class, they will have told you what they expect you to use as tools for input and output, eg char inputChar; cin >> inputChar; or similar. Use whatever they told you to use in the style they want you to use, eg
cout << HEADS_OR_TAILS_PROMPT;
char inputChar;
cin >> inputChar;
switch(inputChar) {
case 'h':
{
... // code for the heads case
break;
}
case 't':
{
... // code for the tails case
break;
}
default:
// whatever you want to do if they didn't input a valid option
}
Although, to be honest, asking your professor is going to get you a better answer for what the grader is expecting than asking us is.

Related

C++: Why/How a Break Statement Works In This Code?

I have started to use C++ programming language as a complete beginner. With the aim of becoming a better programmer for my STEM degree and with the goal of competitive programming in mind. I have started Functions and Loops in C++ recently and there was a problem I was not sure how to approach.
The probelem: "Write a function to check whether a number is prime"
My Approach:
-> I wanted to implement it on my own so I didn't want to copy paste code online where others have used functions with return type bool.
-> Here is the final version of my code that works:
void prime(int k){
for(int k1=2;k1<k;k++){
if(k%k1==0){
cout<<"int is not prime"<<endl;
break;
}
else{
cout<<"int is prime"<<endl;
break;
}
}
}
->I would then call this in int Main() and get the user to input integers and so on.
-> The above code was due to many trial-and-errors on my part and my thought process was as follows: 1)if i don't include the "break;" statement my code results in an infinite loop 2)I needed a way to stop my code from going toward an infinite loop 3) I remember a topic covered in the functions segment of this website , where we can use it to terminate a loop at will. Thats why i incorporated it into my code to produce the final version
My Question:
Can someone explain how the break; statement is working in the context of my code? I know it produces my desired effect but I still haven't gotten an intuition as to how this would do my work.
Many online resources just cite the break statement as something that does so and so and then gives examples. Without going through the code mechanics. Like how a loop would be going through its conditions and then when it encounters the break; statement what does it do? and as a consequence of that what does it do to help my code?
Any advice would be helpful. I still couldn't wrap my head around this the first time I encountered it.
In your case if k % k1 does not show that the k1 being a factor of the k, the loop is broken after the print statement. If the k % k1 does show that the k1 being a factor of the k, it also breaks out of the loop.
So, either of the break statements leads to the loop termination on the first iteration here. If you test for whether a number is being a prime, it does not work.
In essence, you don't need either of the break statements here. They are mostly forced here. Take a look at the following approach:
#include <iostream>
#include <cmath>
bool prime(unsigned k){
if (k != 2) { // Direct check, so to remain similar to the OP's structure of the code
unsigned up_to = sqrt(k) + 1; // Calculate the limit up to which to check
for (unsigned i = 2; i < up_to; ++i) {
if (k % i == 0) {
std::cout << "Is not prime" << std::endl;
return false;
}
else std::cout << "Checking..." << std::endl;
}
}
std::cout << "Is prime" << std::endl;
return true;
}
// Note, we can check just up to the square root of a k
A note on the behavior of the break
The fact that it breaks out the the closest loop to it - has crucial nature for nested loops (all of them: for, while, and do while):
while (/* condition 1 */) // Outer loop
while (/* condition 2 */) // Inner loop
if (/* condition 3 */) break;
Here if the condition 3 is satisfied, the break will lead to break out of the Inner loop but the Outer loop will still continue to iterate.
For more, you may be interested in "How to exit nested loops?" thread. It addresses your second question.
Analogy... I found it in the last place I looked... like always!
Looking for your keys is the LOOP you are in... when you find them... you BREAK out and move on to another task... like maybe getting into your car...
SO if you are IN your car and know your car is where you left your keys... then you are in the PROCESS of getting prepared to drive away... BUT that process requires keys... THUS you change modes/focus and begin a cyclic process of looking for keys... when found to BREAK that searching process IMMEDIATLY and resume what your were doing.
MANY people would make use of the RETURN instrucion in your code pattern... in place of the break! Both do the same thing... however the RETURN is more descriptive english... and one should be concerned with the programmer behind him... Also a bit of digging might show how one is more efficient than the other...

How to compare many booleans to pass through specific outputs? C++ for UE4

I myself am not a programmer, but I have a programmer friend who is trying to help me with a certain task in Unreal Engine 4, and I was hoping to find some advice here to pass on to him.
What we are trying to make is a 'Node' in UE4 that can take in many boolean values (20+), and pass out specific values, or rather to pass through the event chain/line.
For example, I could have 6 booleans coming into the node, and I would want one of the outputs to pass through if boolean 2 and 4 were true, 1 was false, and the rest aren't looked at (essentially N/A). I made a quick image below to showcase what it would look like.
Example Of What Node would look like
My friend says he is not sure how such a node could be accomplished in C++, so I am hoping someone here can help give us a nudge in the right direction. Otherwise, I'll be stuck messing with branch nodes, and nodes, or nodes, and the like till my ears bleed and my project looks like a bowl of spaghetti.
Thanks for the suggestion, but I feel that that implementation is a bit too simple for what I am needing.
Hhhmmm, maybe I can explain my thoughts to the logic of it. Essentially, have the incoming boolean values into the node be made into an array of integers(or floats, dont know the difference between them really), with True = 1, and False = 2. The number of inputs to the array node can be determined by the number of inputs into the main Node.
Then, based on the number of inputs into the main Node, you can that same number of options per each event out pin on the main Node. Each option would have 3 check boxes. Checking the first box would output a 1 for True, second box would output 2 for False, and third box would output 3 for Dont Check.
These outputs could then be made into an array themselves. And then you would just have to compare the two arrays to see if they match, and anywhere there is a 3 value in the second array, that would output an 'is matching' regardless of what it is being compared to.
I just don't know actual coding, so I need a bit of help to try and explain this line of logic to my buddy, in terms of code.
Based on the information:
std::vector<int> input_vector; //the index will represent sequence and value will represent state
for(int i=0; i<node_size; i++)
{
input_vector.push_back(state); //you will push state=1 or state=2 here
}
std::vector<int> node_vector;
bool flag = true;
for(int case_no=0; case_no<cases;case_no++)
{
//checking node_vector with input_vector
for(int i=0; i<node_size; i++)
{
int choice;
std::cin >> choice; //either 1 or 2 or 3
node_vector.push_back(choice);
}
for(int i=0; i<node_size; i++)
{
if(node_vector[i]==3)
continue;
else if(node_vector[i]==input_vector[i])
continue;
else
{
flag = false;
break;
}
}
if(flag==true)
break;
else
continue;
}
if(flag)
std::cout << "Matched";
else
std::cout << "Not Matched";

While Loop how to?

I have a test in a couple of days and I was reviewing the study guide and I came across a question that I wasn't familiar with. It says "Write a while loop that continuously loops until the user inputs a number saved in a variable named myNum between -1 and -100. Use only < and > operators." Can someone give me a clear explanation of what exactly I am supposed to do for this question?
I'm honestly not entirely sure what this question is asking, because it seems a bit ambiguous in the wording, but this is what I would assume they are asking for. I'm not sure how you could get this done with "only" > and < operators, as you need input and possibly output operators (>> and << respectively). Anyway, I hope that this helps, and if its not perfectly correct with what your assignment is, maybe you can see the logic and make the small changes to have it fit better.
I commented each line, even the obvious (which is sort of a no-no when you get into heavier coding), this way all the syntax makes sense.
#include <iostream>
using namespace std;
int main()
{
// Initialize myNum to 1 so that it passes into while-loop
int myNum = 1;
// Continue looping as long if number is less than -100 or greater than -1 (terminating the loop when numbers from -100 to -1 are entered)
while((myNum > -1) || (myNum < -100))
{
// Display "Enter Text" to console
cout << "Enter number: ";
// Allow user to input number
cin >> myNum;
}
}

I have an error with my return statements that I don't know to fix

In a text adventure game that I am making, all the different places are run my different functions. In my diner, market, and supply store, I have a switch statement that takes numbers 1-10. All 1-9 work, but 10 doesn't. All of these methods return back to a method called TownCenter(), but on these 3, when I do return, you have to spam it in order for it to work. Here is a code example:
void Diner(){
int answer;
cout << "Blah, blah. Type '0' to go back to town.\n";
cin >> answer;
switch (answer){
case 0:
return;
break;
}
Diner()
}
Every time you type 0, it would just go to Diner() again. It eventually works if you spam 0 over and over, but why won't it work all the time?
I don't think there is any error with the code, except for the following considerations:
Missing semicolon after Diner() in line 10.
The break; statement is not required as return; is being used before it.
I don't think you mean to use recursion here. I would suggest using while loops while people are in individual locations. By calling the same location again at the end of your case statement to go back to the same area, you are going deeper in the callstack, requiring more "exits" to "leave" the room.
A do-while loop like the following would work nicely:
int answer;
do {
cout << "Blah, blah. Type '0' to go back to town.\n";
cin >> answer;
switch (answer){
// other case statements
case 0:
break;
}
} while (answer != 0);
Notice I don't call Diner() again at the end. Getting it to process the same room until the "leave" is accomplished by the loop instead of unnecessary recursion.

C++ input of type char, output of type int

I am taking my very first C++ class and I am stuck. I would really appreciate some help from you experienced programmers.
The assignment is creating a blackjack-scoring program. Not a very realistic one, but hey. The user inputs how many cards he wants and then the values of each of those cards. The assignment specifies that the inputs should be in type char. So if the user has a 2 card they enter 2, but that 2 is actually char and must be converted to int. Or they would enter "Q" if they have a queen and my program is supposed to convert that Q to ten points for scoring. I cannot figure out what is the right way to do this. The assignment suggests I will use either a switch statement or nested if-else statement, but I am afraid I don't understand switch very well from the book examples.
So here's a tiny bit of my attempts at switch. *points_for_card* is of type char and *number_value* is int.
switch (points_for_card)
{
case '2':
number_value = 2 ;
break;
case '3':
number_value = 3 ;
break;
// ETC
}
So what I am going for here is: if the user enters '3' as a char, it becomes int 3. But maybe this is not how switch works at all.
The thing is, my program compiles and works, but returns weird crazy huge numbers. If I move points_for_card to int instead of char, then the arithmetic works perfectly for whatever numbers I enter, because at that point it's just adding them together.
I hope I explained this ok, will clarify as much as possible if necessary.
it can be something like this code:
if (points_for_card >= '1' && points_for_card <= '9'){
number_value = points_for_card - '0'; // convert to number
}else if (points_for_card == 'Q'){
...
}
A map comes to mind. You can store the scores directly, or you can make one map to look up the card type and other maps to associate other information (like score) to each card. Here's the baby example:
std::map<char, int> scores;
scores['Q'] = 10; scores['A'] = 13; scores['2'] = 2; // etc.
char c;
std::cout << "Please enter a card: ";
std::cin >> c;
std::cout << "Your card has score " << scores[c] << std::endl;
Oftentimes when your heart says "switch", your brain should say "map" :-)
Personnally I'd define an enum ECardType { Card_2, ..., Card_10, Card_Jack, ... }; and have one map be std::map<char, ECardType>, and then other maps from card type to secondary information like scores.
How are you taking inputs into points_for_card ?
Your input should be cin >> points_for_card;
Instead of comparing a character to a character, you can also compare it to the ASCII value of a character.
For example,
char letter = 'A'
if(letter == 65){
cout << "Match";
}
The above code will output "Match!".
Also, your switch statements are perfectly worded. The problem lies elsewhere in your program, so please provide the relevant source.
Another point related to your program but not your problem: How are you dealing with Aces ? You know that they can be counted as either 1 or 11, depending on the player's hand value, right ?