Re run a c++ program based on user input or condition - c++

I'm learning c++ and as an exercise with arrays and user input, I'm trying to write a simple poker application.
Since I'm at the begin of this course, all I know about the c++ language is that the execution of the code is demanded to the main() function. I've write some lines of code that is the base of the final app, it works fine for now. I want to implement a loop to re run the app based on the user input and on a condition that for the scope of the app will be the amount of th fish variable quantity after every execution. How I can achieve this? Another question is about the use of random elements from an array. Is there any good reference where I can learn how to do this?
This is my code:
#include <iostream>
using namespace std;
int main(){
string name;
int bet;
int fish = 100;
char seed[4][10] = {"hearts","clubs","diamonds","spades"};
int cards[9] = {2,3,4,5,6,7,8,9,10};
std::cout << "Welcome in PokerBash! Please enter your name:" <<std::endl;
std::cin >> name;
std::cout << "Your name is " << name <<std::endl;
std::cout << "You have a credit of:" << fish <<std::endl;
std::cout << "Please enter your bet:" <<std::endl;
std::cin >> bet;
std::cout << "Your cards are " << seed[2] << " " << cards[3] << " " << seed[1] << " " << cards[7] <<std::endl;
std::cout << "Your credits after this bet:" << fish - bet <<std::endl;
return 0;
}

You can do a loop that stops if the user wants to or fish is less than 0 by making a while loop that depends on some boolean playing that is initially true. So if one of the two events happen, set playing to be false and the loop stops:
int main() {
//variables
bool playing = true;
while (playing) {
int fish = 100;
//poker game
if (fish < 0) { //no money
playing = false;
}
else {
char input;
std::cout << "would you like to play again? (y/n): ";
std::cin >> input;
if (input != 'y') {
playing = false;
}
}
}
}
as you can see, this repeats until I enter something that isn't 'y':
would you like to play again? (y/n): y
would you like to play again? (y/n): y
would you like to play again? (y/n): n
to choose a random element from an array you would use the utilities from <random> like their std::mersenne_twister_engine. To get a random element from an array you would basically just need create a random number and use that as the arrays index:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937_64 engine(rd());
std::uniform_int_distribution<int> distribution(0, 8);
int cards[9] = { 2,3,4,5,6,7,8,9,10 };
while (true) {
std::cout << cards[distribution(engine)] << '\n';
}
}
some important things from here:
std::random_device rd;
std::mt19937_64 engine(rd());
is done only once (never in a loop). It is for initializing your pseudo random generator engine.
std::uniform_int_distribution<int> distribution(0, 8);
adds a distribution. Note that, because your int cards[9] has 9 elements, the range has to go from 0 to 8 as arrays start at 0and end at their size - 1, as you might probably already know. :)
Running this you can see it randomly prints out the card numbers from 2 to 10:
2
10
7
9
2
4
9
10
8
9
8
6
8
2
10
These are your helping points to implement further. I add some more things I noticed about your code but are not necessary to the question itself.
You should note that you should not use namespace std - you can read here why.
Also, instead of:
char seed[4][10] = { "hearts","clubs","diamonds","spades" };
use:
std::string seed[4] = { "hearts","clubs","diamonds","spades" };
To use std::string include the <string> header.
you wrote std::cin >> name; but this doesn't work for strings with spaces, like look here:
Welcome in PokerBash! Please enter your name:
Stack Danny
Your name is Stack
To get the full name, use
std::getline(std::cin, name);

Try this,
#include <iostream>
using namespace std;
int main()
{
string name;
int bet;
int fish = 100;
char seed[4][10] = {"hearts", "clubs", "diamonds", "spades"};
int cards[9] = {2, 3, 4, 5, 6, 7, 8, 9, 10};
while (1)
{
std::cout << "Welcome in PokerBash! Please enter your name ( Enter q to quit ):" << std::endl;
std::cin >> name;
if(name == "q")
exit(0);
std::cout << "Your name is " << name << std::endl;
std::cout << "You have a credit of:" << fish << std::endl;
std::cout << "Please enter your bet:" << std::endl;
std::cin >> bet;
std::cout << "Your cards are " << seed[2] << " " << cards[3] << " " << seed[1] << " " << cards[7] << std::endl;
std::cout << "Your credits after this bet:" << fish - bet << std::endl;
}
return 0;
}

Related

Parallel arrays to create a database to store animal types and counts for C++

This is what it's suppose to look like
Am I doing this correctly? and what another coding I need to do to display like this. I have to simulate a database to store animal types and animal type count. I have to use parallel arrays for data storage. It would be better if I make this dynamically allocated array of no mroe than 5 elements.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int MAX_RECORDS = 5;
const int ADD = 1, DISPLAY = 2, EXIT = 3;
void addAnimal();
void displayAnimal();
int main()
{
int choice, animal;
int a = 0;
do
{
cout << "How many animal records would you like to store (5 max): ";
cin >> animal;
cout << endl;
cout << "1. Add animal(s)" << endl;
cout << "2. Display animals" << endl;
cout << "3. Quit" << endl;
cout << endl;
do
{
cout << "Please enter a menu number: ";
cin >> choice;
if (choice <= 0 || choice > EXIT)
{
cout << "Error. Please try again.\n";
cout << endl;
}
} while (choice <= 0 || choice > EXIT);
// Create a muliway branch statement.
switch (choice)
{
case ADD:
addAnimal();
break;
case DISPLAY:
displayAnimal();
break;
case EXIT:
break;
}
} while (choice != EXIT);
cout << endl;
system("pause");
return 0;
}
void addAnimal()
{
string str;
do
{
cout << "Please enter an animal type (none to stop): " << endl;
getline(cin, str);
cout << "Enter the animal type's count: " << endl;
getline(cin, str);
} while (str != "goodbye");
}
void displayAnimal()
{
}
Another good way to achieve what you want is to inculcate Object-Oriented programming into this. Here is a simple structure of Animals that can be used to create an array of 5 objects.
Take this short example
#include<iostream>
struct Animal{
std::string name;
int value;
int weight;
}animals[5]; // creates an animal object array of size 5
int main(){
for (int i = 0;i < 5;i++){
std::cout << "Name of animal number " << i+1 << ": ";
std::cin >> animals[i].name;
}
std::cout << animals[0].name;
}
Output:
Name of animal number 1: Tiger
Name of animal number 2: Lion
Name of animal number 3: Kangaroo
Name of animal number 4: Cheetah
Name of animal number 5: Dog
Tiger
Process returned 0 (0x0) execution time : 23.463 s
Press any key to continue.
Information on what is going on in this program.
When I say struct Animal I am creating a structure. Animals all have similar features like weight, color, name etc. Those are the variables that will be present inside the body of the structure.
`animals[5]'. Think of this as an array of animals. Animals that have common attributes like weight, color, name etc. Assume the user wants to create a new animal and enter it's features. I can use one element from the array to do this. Let's use the first one.
std::cout << "Enter name: ";
std::cin >> animals[0].name;
std::cout << "Enter weight: ";
std::cin >> animals[0].weight;
std::cout << "Enter value: ";
std::cin >> animals[0].value;
Now the first element of animals has been initialised. You can access it by animals[0].attribute
This approach will work effeciently for this kind of a program. Refer to this.
In my example I have taken input of all 5 elements using a loop. You can do the same when the user wants.
For your purpose, I would suggest you use std::vector<>.Below is a basic implementation of using vectors in C++.
Note: You need to mention #include<vector> at the top.
#include<vector>
#include<iostream>
int main(){
std::vector<int> my_vec; // initializing a vector of integers
// To add anything to a vector, you can use
my_vec.push_back(5); // Adds 5 to my_vec
my_vec.push_back(6); // Adds 6 to my_vec
std::cout << my_vec[0] << std::endl; // Slicing from a vector
for(auto it:my_vec) std::cout << it << std::endl; // display contents
return 1;
}
I cannot show you everything about vectors in this answer, it's another huge topic. The main idea is that they are dynamic and can change size during run-time. compared to traditional static arrays.
vectors in C++
Perhaps consider using an std::map. You can add as many animals as you want. Each animal name, in this case, will have an associated count. In the example below, when the program exits, it will print out everything that you added to the map.
#include <iostream>
#include <map>
#include <string>
int main()
{
std::map<std::string, int> animal_database;
std::string animal_name;
std::string animal_count;
std::string in_val;
while (1)
{
std::cout << "Enter an animal name: ";
std::cin >> animal_name;
std::cout << "Enter animal count: ";
std::cin >> animal_count;
animal_database.insert(std::pair<std::string, int>(animal_name, std::stoi(animal_count)));
std::cout << "Would you like to to add another animal?: [Y] or [N] ";
std::cin >> in_val;
if (in_val == "N" || in_val == "n")
break;
}
for (std::map<std::string, int>::iterator it = animal_database.begin(); it != animal_database.end(); ++it)
{
std::cout << it->first << " " << it->second << std::endl;
}
}

How to read in a String with white space in C++ [duplicate]

This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 3 years ago.
so I'm working on a homework problem for my CS175 C++ course. We have a homework assignment where we have to make a shorting hat, kinda like what's in Harry Potter. I've got 99% of the code down, however the thing that is tripping me up is how to read in a string with white space.
We need to be able to input full names so obviously just using std::cin >> won't work. The problem is that I can't seem to get any of the methods to work that I've tried so far.
This is my code:
#include <iostream>
#include <string>
int main()
{
int NumStudents;
std::string NameStudents;
int StartValue;
int House;
std::string HouseName;
int NumCornfolk = 0;
int NumEsophagus = 0;
int NumBob = 0;
//How many students are there?
std::cout << "How many students are there? \n";
std::cin >> NumStudents;
for (StartValue = 0; StartValue < NumStudents; StartValue++) {
std::cout << "Please enter the name of the next student. \n";
std::cin >> NameStudents; \\**THE PROBLEM IS HERE**
//Assings the House
House = rand() % 100 + 1;
if (House <= 19) {
HouseName = "Cornfolk! \n";
NumCornfolk++;
}
else if (House > 19 && House < 50) {
HouseName = "Esophagus! \n";
NumEsophagus++;
}
else if (House >= 50) {
HouseName = "Bob! \n";
NumBob++;
}
std::cout << NameStudents << " got " << HouseName << std::endl;
}
//Prints Results
std::cout << "Number of Students in each House: \n";
std::cout << "Cornfolk:" << NumCornfolk << " Esophagus:" << NumEsophagus << " Bob:" << NumBob;
}
The line of code that reads std::cin >> NameStudents; is what's causing the problem. I've seen methods that say to use something along the lines of "std::cin.getline (name,256);" but cin.getline throws an error at the period and won't compile.
Being able to read in the names correctly is only 2/11 points, so it's not that big of a deal, but I would like to know why the suggested methods are not working here.
Thank you. This question is different from ones asked before mods.
Use std::getline, like this:
std::getline(std::cin, NameStudents);
Here's an example from https://en.cppreference.com/w/cpp/string/basic_string/getline:
std::string name;
std::cout << "What is your name? ";
std::getline(std::cin, name);
std::cout << "Hello " << name << ", nice to meet you.\n";

C++ - I´m coding my first program, but I ran into some trouble

I have started to learn C++ lately and wanted to make my first "game"/program. I have run into some difficulties.
My errors so far are as follows:
(rand()%a) -> changing "a" doesn´t do anything (for example if the generated number is 2 and "a" is 1 the generated number stays 2).
The following code does not work:
while(!(b = c)){
cout << "Enter your guess! \n";
cin >> c;
if(c<b){
cout << "Bigger! \n";
}
if(c>b){
cout << "Smaller! \n";
}
d++;
}
My complete program is as follows:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
// Max. Limit
int a;
// Random Number
int b;
// Guess
int c;
// Tries counter
int d = 0;
cout << "Enter highest possible number, setting the max. limit for the program. \n";
cin >> a;
srand(time(0));
b = 0 + (rand()%a);
if(b =! 1){
c = 1;
}
if(b = 1){
c = 2;
}
while(!(b = c)){
cout << "Enter your guess! \n";
cin >> c;
if(c<b){
cout << "Bigger! \n";
}
if(c>b){
cout << "Smaller! \n";
}
d++;
}
if(b=c){
cout << "Congratulations! You have guessed was right! The number was indeed " << b << " !" << endl;
cout << "You needed " << d << " tries to find the number! \n";
}
return 0;
}
Alright, the first thing you need to know is (as drescherjm already pointed out), b = c is not what you want here. Instead, you want b == c for comparison.
Another thing is:
if(b =! 1){
c = 1;
}
if(b = 1){
c = 2;
}
You can avoid initializing c to a different value than b by replacing your while-loop with a do-while-loop. If you then also get rid of using namespace std; and use <random> instead of rand(), rename your short variables (a, b) to what they are actually doing, you're code becomes clearer and more modern.
#include <iostream>
#include <random>
int main()
{
int max_limit{ 0 };
int random_number{ 0 };
int guess{ 0 };
int number_of_guesses{ 0 };
std::cout << "Enter highest possible number, setting the max. limit for the program. \n";
std::cin >> max_limit;
std::random_device now;
std::mt19937 engine(now()); //random seed
std::uniform_int_distribution<int> r(0, max_limit); //range
random_number = r(engine);
do{
std::cout << "Enter your guess! \n";
std::cin >> guess;
if (guess<random_number){
std::cout << "Bigger! \n";
}
if (guess>random_number){
std::cout << "Smaller! \n";
}
number_of_guesses++;
} while (random_number != guess); //do the code above until this is false
std::cout << "Congratulations! Your guess was right! The number was indeed " << random_number << " !" << std::endl;
std::cout << "You needed " << number_of_guesses << " tries to find the number! \n";
return 0;
}
Example run:
Enter highest possible number, setting the max. limit for the program.
100
Enter your guess!
50
Smaller!
Enter your guess!
25
Smaller!
Enter your guess!
10
Bigger!
Enter your guess!
15
Congratulations! Your guess was right! The number was indeed 15 !
You needed 4 tries to find the number!
So yeah, that's working.
a = b assigns a the value of b
a == b compares de values of both variables.
About first problem, check about seed.

My function is being seemingly being skipped for no reason

Attempting a basic C++ challenge, (beginner at C++) and I produced this code. I understand that calling a value in an array starts from zero but I wanted the user to type from 1-5 instead of 0-4 because I didn't want to go the easy route and wanted to see if I could do it.
Here is my problem, I made a basic function to subtract 1 from the int choice to allow the user to enter 1-5 but the array see the value as 1-4. However as shown in this image it seems to ignore my function and skip to the next part of the code. I have included my code below.
#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
string drink[5] = { "Coke", "Water", "Sprite", "Monster", "Diet Coke" };
int choice;
int correct = 0;
void AdjArray()
{
choice--;
};
int main()
{
while (correct != 1)
{
cout << "Enter the number of the beverage you would like." << endl;
cout
<< " Coke = 1\n Water = 2\n Sprite = 3\n Monster = 4\n Diet Coke = 5"
<< endl;
cin >> choice;
AdjArray;
if (choice >= 0 && choice <= 4)
{
cout << "You have chosen " << drink[choice] << "." << endl;
correct = 1;
}
else
{
system("cls");
cout << "Error, you entered: " << choice
<< ". Please enter a number between 1 and 5.\n" << endl;
}
}
return 0;
}
You're not calling your function. Change AdjArray; to AdjArray();

Arrays and For Loops: Creating a list of numbers Greatest to Least

#include <iostream>
using namespace std;
int main() {
int greatestToLeastPancakeAmount[10] = {};
int greatestToLeastPersonNumber[10] = {};
int pancakeAmount;
int x;
cout << "Pancake Glutton 1.0 \n\n"; //State program's title
cout << "10 Different people ate pancakes for breakfast.. \n\n";
x = 0;
for(x=0;x<10;x++) {
cout << "How many pancakes did person " << (x + 1) << " eat? > ";
cin >> pancakeAmount;
greatestToLeastPersonNumber[x] = (x + 1);
greatestToLeastPancakeAmount[x] = pancakeAmount;
/*while(pancakeAmount > greatestToLeastPancakeAmount[(x - 1)]) {
int storeGreatestToLeastPancakeAmount = greatestToLeastPancakeAmount[(x-1)];
int storeGreatestToLeastPersonNumber = greatestToLeastPersonNumber[(x-1)];
greatestToLeastPancakeAmount[(x-1)] = pancakeAmount;
greatestToLeastPersonNumber[(x-1)] = x;
greatestToLeastPancakeAmount[x] = storeGreatestToLeastPancakeAmount;
greatestToLeastPersonNumber[x] = storeGreatestToLeastPersonNumber;
}*/
}
cout << "\n\n";
for(x=0;x<10;x++) {
cout << "Person " << greatestToLeastPersonNumber[x] << " ate " << greatestToLeastPancakeAmount[x] << " pancakes!\n";
}
return 0;
}
How do I accomplish outputting the number of people that ate the most pancakes followed by the people that at the least amount of pancakes?
Let's start with the general requirement: You always need to verify after reading that you successfully read whatever you tried to read, e.g.:
if (!(std::cin >> greatestToLeastPancakeAmount[x])) {
std::cout << "failed to read number of pancakes (ignoring this line)\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Next, there isn't really a need to store any identifier for the persons:
It isn't needed.
The stored identifier is always i + 1 where i is index anyway.
With your setup the easiest approach to compute the number of persons who ate the most or least amount of pancakes is probably to std::sort() the array and then count the number of equal counts at the start and the end of the array. An easier approach entirely is, however, to just stick increment a value in a std::map<int, int> and then output the first and the last element of the map:
std::map<int, int> count;
for (int i = 0; i != 10; ++i) {
++count[greatestToLeastPancakeAmount[i]];
}
if (count.empty()) { // won't happen until you start tracking the number of people entered
std::cout << "nobody ate any pancake\n";
}
else {
std::cout << (--count.end())->second << " persons ate " << (--count.end())->first
<< " pancakes\n";
std::cout << count.begin()->second << " persons ate " << count.begin()->first
<< " pancakes\n";
}