How can I Terminate Vector Input Using if statement in C++ - c++

Does anybody have a simple solution to terminate a for loop that inputs values for a vector when a specific value is placed into the vector, but does not store that specified value into the vector?
I have created a random number generator that creates "n" unique values for a vector of size "n". However, when I run my code, the word "done" pops up and the program crashes.
Here is the code:
int main()
{
int i = 0;
vector<int> playerIndex;
vector<int> randGenNum;
vector<string> players;
vector<string> team1;
vector<string> team2;
vector<string> team3;
vector<string> team4;
cout << "Welcome to the Team Selector. \n" << endl;
cout << "A random team of two will be generated for you all." << endl;
cout << "When you are finished entering player names, enter the word \"done\". " << endl;
cout << "Enter the name of the players: \n" << endl;
for(string name; cin >> name;){
players.push_back(name);
if(name == "done"){
players.erase(players.end() - 1);
break;
}else{
playerIndex.push_back(i);
i++;
}
}
cout << "\n";
cout << "Player names: \n";
for(int a=0; a < players.size(); a++){
cout << a + 1 << " - " << players[a] << endl;
}
srand(time(0));
int b =0;
int randNum;
while(b < players.size()){
randNum = 1 +(rand()%players.size());
if(find(randGenNum.begin(), randGenNum.end(), randNum)!= randGenNum.end()){
while(find(randGenNum.begin(), randGenNum.end(), randNum)!= randGenNum.end()){
randNum = 1 +(rand()%players.size());
}
randGenNum.push_back(randNum);
b++;
}else{
randGenNum.push_back(randNum);
b++;
}
}
cout << "\n" <<"This is a test" << endl;
for (int c=0; c < players.size(); c++){
cout << "Generated #: " << randGenNum[c] << endl;
}
int totalPlayers = players.size();
int firstPlayer = randGenNum[0];
int secondPlayer = randGenNum[1];
int thirdPlayer = randGenNum[2];
int fourthPlayer = randGenNum[3];
int fifthPlayer = randGenNum[4];
cout << "\n";
cout << "Team 1 is: " << players[firstPlayer] << " and "<< players[secondPlayer] << "\n" << endl;
cout << "Team 2 is: " << players[thirdPlayer] << " and " << players[fourthPlayer] << "\n" << endl;
return 0;
}

Problem
players.end() - 1 is not a valid iterator.
Solutions 1:
Check the item before adding it to the vector.
for(string name; cin >> name;) {
if(name != "done")
{
players.push_back(name);
playerIndex.push_back(i);
i++;
}
}
Solutions 2:
Use std::vector::pop_back().
for(string name; cin >> name;){
players.push_back(name);
if(name == "done"){
players.pop_back();
break;
}else{
playerIndex.push_back(i);
i++;
}
}

Related

Keep receiving this error main.cpp:9:91: error: no match for ‘operator<<’ (operand types are ‘std::basic_ostream’ and ‘const std::vector’

Sorry in advance if this is lengthy. the problem is within line 9. (where the 2nd cout is.) apparently, but i'm new to this so I can't identify exactly what the issue is.
#include <iostream>
#include <vector>
using namespace std;
void outputRoster(const vector<int> &jersey, const vector<int> &ratings) {
cout << "ROSTER" << endl;
for (int i =1; i < jersey.size(); ++i) {
cout << "Player " << i << " -- Jersey number: " << jersey.at(i-1) << ", Rating: " << ratings << endl;
}
cout << endl;
}
void addPlayer(vector<int> &jersey, vector<int> &ratings) {
int num;
cout << "Enter another player's jersey number: ";
cin >> num;
jersey.push_back(num);
cout << "Enter another player's ratings: ";
cin >> num;
cout << endl;
ratings.push_back(num);
}
void removePlayer(vector<int> &jersey, vector<int> &ratings) {
int num;
cout << "Enter a jersey number: ";
cin >> num;
cout << endl;
for (int i = 0; i < jersey.size(); ++i){
if (jersey.at(i)==num){
jersey.erase(jersey.begin()+i);
ratings.erase(ratings.begin()+i);
break;
}
}
}
void updatePlayerRating(const vector<int> &jersey, vector<int> &ratings){
int num;
cout << "Enter a jersey number: " << endl;
cin >> num;
for (int i = 0; i < jersey.size(); ++i){
if(jersey.at(i) == num){
cout << "Enter a new rating for player: ";
cin >> num;
cout << endl;
ratings.at(i) = num;
}
}
}
void outputPlayersAboveRating(const vector<int> &jersey, const vector<int> &ratings) {
int num;
cout << "Enter a rating: ";
cin >> num;
cout << endl;
cout << "ABOVE " << num << endl;
for (int i = 0; i < ratings.size(); ++i){
if (ratings.at(i) > num) {
cout << "Player " << i+1 << " -- Jersey number: " << jersey.at(i) << ", Rating: " << ratings.at(i);
}
}
cout << endl;
}
int main() {
vector<int> jersey;
vector<int> ratings;
for (int i = 0; i < 5; ++i) {
int num;
cout << "Enter player " << i+1 << "'s jersey number:";
cin >> num;
jersey.push_back(num);
cout << "Enter player " << i+1 << "'s ratings:";
cin >> num;
ratings.push_back(num);
cout << endl;
cout << endl;
}
outputRoster(jersey, ratings);
char inp;
while(true) {
cout << "MENU" << endl;
cout << "a - Add player" << endl;
cout << "d - Remove player" << endl;
cout << "u - Update player rating" << endl;
cout << "r - Output players above a rating" << endl;
cout << "o - Output roster" << endl;
cout << "q - Quit" << endl;
cout << "Choose an option: ";
cin >> inp;
cout << endl;
if (inp == 'a') {
addPlayer(jersey, ratings);
}
else if (inp == 'd') {
removePlayer(jersey, ratings);
}
else if (inp == 'u') {
updatePlayerRating(jersey, ratings);
}
else if (inp == 'r') {
outputPlayersAboveRating(jersey, ratings);
}
else if (inp == 'o') {
outputRoster(jersey, ratings);
}
else if (inp == 'q') {
return 0;
}
}
return 0;
}
Any and all help is appreciated also if possible, could you explain how to avoid an error like this in the future.
Thanks in advance.
You cannot print ratings directly in
cout ... << ratings ... because std::vector doesn't have an operator overload for printing. Rather, you have to print out an element inside that vector, so change it to cout ... << ratings[i] ..., which I'm assuming is your desired effect.
This is exactly what the compiler error is telling you. std::vector doesn't have an overload (no operator<< match).

How to only print out highest/smallest array values in c++

Good day, I'm having difficulty on the last two parts of my program where it's supposed to only output players who got maximum/minimum scores, I need help on how to do it because I'm really confused. If it's also alright to provide some explanations I'd really appreciate it.
I tried this approach:
#include <iostream>
using namespace std;
int main() {
double lrgst, lrgst2, lrgst3;
int numbers[5];
lrgst = lrgst2 = lrgst3;
for (int i = 0; i < 5; i++) {
cin >> numbers[i];
}
for (int i = 0; i < 5; i++) {
if (numbers[i] > lrgst) {
lrgst3 = lrgst2;
lrgst2 = lrgst;
lrgst = numbers[i];
} else if (numbers[i] > lrgst2) {
lrgst3 = lrgst2;
lrgst2 = numbers[i];
} else if (numbers[i] > lrgst3) {
lrgst3 = numbers[i];
}
}
cout << "largest are: " << lrgst << " " << lrgst2 << " " << lrgst3;
}
this is my actual code:
#include <iostream>
using namespace std;
struct playerdata {
char name[50];
int age, score1, score2;
double average;
};
int main() {
int choice, i = 1, j = 1, z = 1, backtomain2;
char backtomain;
playerdata p1[10];
do {
for (int a = 0; a < 47; a++) {
cout << "=";
}
cout << "\n";
for (int b = 0; b < 22; b++) {
cout << " ";
if (b == 21) {
cout << "MENU \n";
}
}
for (int c = 0; c < 47; c++) {
ocut << "=";
}
cout << " "
"\n1. Add record\n"
"2. View players records\n"
"3. Compute for the average\n"
"4. Show the player(s) who gets the max average.\n"
"5. Show the player(s) who gets the min average.\n"
"6. Exit\n"
"Enter your choice:";
cin >> choice;
if (choice == 1) {
cout << "Add player data" << endl;
do {
cout << "Enter player " << i << " nickname:";
cin >> p1[i].name;
cout << "Enter player " << i << " age:";
cin >> p1[i].age;
cout << "Enter player " << i << " score 1:";
cin >> p1[i].score1;
cout << "Enter player " << i << " score 2:";
cin >> p1[i].score2;
cout << "Enter again? (Y/N)";
cin >> backtomain;
i++;
}
while (backtomain != 'N' && backtomain != 'n' && i < 7);
if (choice == 2) {
cout << "Player records" << endl;
cout << "Player nickname "
<< "Player age "
<< " player score 1"
<< "
player score 2\n ";
for (z = 1; z <= i - 1; z++) {
cout << p1[z].name << " " << p1[z].age << "" << p1[z].score1 << ""
<< p1[z].score2 << "\n";
}
cout << "Press 1 to go back to main menu\n";
cin >> backtomain;
}
if (choice == 3) {
cout << "Computing for average...\n";
for (int d = 1; d <= i - 1; d++) {
p1[d].average = (p1[d].score1 + p1[d].score2) / 2.0;
cout << "\n" << p1[d].average << "\n";
}
cout << "Press 1 to go back to main menu\n";
cin >> backtomain;
}
if (choice == 4) {
cout << "Player(s) who got the max average:\n";
cout << "\nPress 1 to go back to main menu";
cin >> backtomain;
}
if (choice == 5) {
cout << "player(s) who got the min average: \n";
cout << "Press 1 to go back to main menu";
cin >> backtomain;
}
}
while (choice != 6);
}
You can simply sort the array of players for that
int n = sizeof(p1)/ sizeof(p1[0]);
sort(p1, p1+n, compPlayer);
//larget at pl[0]
//smallest at pl[9]
where
bool compPlayer(playerdata p1, playerdata p2) {
return (p1.score1+p1.score2) > (p2.score1+p2.score2);
//use score incase average has not been calculated for all players yet
}

How to score yahtzee in c++

I am writing a yahtzee game for my c++ programming class. One of my difficulties I have ran into is the scoring system for different categories. I think I have figured out how to do it for adding 1s, 2s etc but I do not know how to have the program determine when a 3 of a kind, 4 of a kind, etc has been rolled. Here is my code so far.
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//Declare variables
int players;
int turn = 1;
vector<string> names;
string playerName;
int dice[5];
int finalScore = 0;
char reroll[5];
char rollDice;
int tries = 1;
const int DICE = 5;
int roll[DICE];
int scorecard;
int scoreThisTurn(int scorecard);
int turnScore = 0;
//Introduction, get number of players.
cout << "Hello, welcome to Yahtzee! How many players are there?" << endl;
cin >> players;
if (players > 4) {
cout << "Sorry, the maximum number of players is 4." << endl;
cout << "How many players are there?" << endl;
cin >> players;
}
//Get player names
string getNames();
for (int i = 0; i < players; i++) {
cout << "Hello player " << i + 1 << ", please enter your name" << endl;
cin >> playerName;
names.push_back(playerName);
}
srand(time(NULL)); //random seed
cout << "Welcome to Yahtzee!\n";
while (turn <= 13) { //roll dice
cout << "Press 'r' to roll" << endl;
cin >> rollDice;
if (rollDice == 'r') {
for (int i = 0; i < DICE; i++) {
roll[i] = rand() % 6 + 1;
}
}
cout << "You rolled: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
cout << "Type y to reroll or n to keep. For example yynnn would keep the first three dice" << endl;
cin >> reroll[0] >> reroll[1] >> reroll[2] >> reroll[3] >> reroll[4];
for (int i = 0; i < DICE; i++) {
if (reroll[i] == 'y') {
roll[i] = rand() % 6 + 1;
}
else if (reroll[i] == 'n') {
roll[i];
}
else cout << "Sorry you entered an invalid letter." << endl;
}
cout << "Your second roll is: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
cout << "Type y to reroll or n to keep. For example yynnn would keep the first three dice" << endl;
cin >> reroll[0] >> reroll[1] >> reroll[2] >> reroll[3] >> reroll[4];
for (int i = 0; i < DICE; i++) {
if (reroll[i] == 'y') {
roll[i] = rand() % 6 + 1;
}
else if (reroll[i] == 'n') {
roll[i];
}
else cout << "Sorry you entered an invalid letter." << endl;
}
cout << "Your third roll is: " << roll[0] << ", " << roll[1] << ", " <<
roll[2] << ", " << roll[3] << ", " << roll[4] << endl;
//displays scorecard categories
cout << "Which category would you like to score this in" << endl;
cout << "1 - ones: " << endl;
cout << "2 - twos: " << endl;
cout << "3 - threes: " << endl;
cout << "4 - fours: " << endl;
cout << "5 - fives: " << endl;
cout << "6 - sixes: " << endl;
cout << "7 - 3 of a kind: " << endl;
cout << "8 - 4 of a kind: " << endl;
cout << "9 - small straight: " << endl;
cout << "10 - large straight: " << endl;
cout << "11 - full house: " << endl;
cout << "12 - yahtzee: " << endl;
cout << "13 - chance: " << endl;
//asks player to choose where to score
cout << "\nEnter 1-14 to choose a category." << endl;
cin >> scorecard;
//assigns points
for (int i = 0; i < DICE; i++) {
turnScore = 0;
if (scorecard == 1) {
if (roll[i] == 1) {
turnScore = turnScore + 1;
}
}
if (scorecard == 2) {
if (roll[i] == 2) {
turnScore = turnScore + 2;
}
}
if (scorecard == 3) {
if (roll[i] == 3) {
turnScore = turnScore + 3;
}
}
if (scorecard == 4) {
if (roll[i] == 4) {
turnScore = turnScore + 4;
}
}
if (scorecard == 5) {
if (roll[i] == 5) {
turnScore = turnScore + 5;
}
}
if (scorecard == 6) {
if (roll[i] == 6) {
turnScore = turnScore + 6;
}
if (scorecard == 7) {
if (roll[i] == 2) {
turnScore = turnScore + 2;
}
}
}
cout << scorecard << endl;
turn++;
}
system("pause");
return 0;
}
As you can see I've set up the scoring for the first 6 categories but don't know how to proceed.
I do not know how to have the program determine when a 3 of a kind, 4 of a kind, etc has been rolled.
Create a variable to help you keep track of the number of dice that have a given number.
int diceCount[DICE] = {0};
and fill up the array with:
for (int i = 0; i < DICE; i++) {
diceCount[roll[i-1]]++
}
Create helper functions to determine whether five, four, or three of a kind have been thrown.
int getNOfAKind(int diceCount[], int N)
{
// This will need moving DICE out of `main`
// making it a global variable.
for ( int i = 0; i < DICE; ++i )
{
if (diceCount[i] == N )
{
return i+1;
}
}
return -1;
}
int getFiveOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 5);
}
int getFourOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 4);
}
int getThreeOfAKind(int diceCount[])
{
return getNOfAKind(diceCount, 3);
}
and use it as:
int fiveCount = getFiveOfAKind(diceCount);
if ( fiveCount != -1 )
{
}
int fourCount = getFourOfAKind(diceCount);
if ( fourCount != -1 )
{
}
int threeCount = getThreeOfAKind(diceCount);
if ( threeCount != -1 )
{
}

How does selection sort work?

This is a selection sort that I'm trying and I don't understand why it isn't working. My understanding is that selection sort scans a vector for the smallest value which when it finds it moves it to the beginning of the vector. It preforms another scan this time ignoring the first element and doing it all over again until n - 1 times where n is the length of the vector.
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <map>
using namespace std;
int main()
{
vector <string> vName, vID, vClass;
string sName, minValue, sID, sClass, sSearch, sQuestion, ssSearch, sSearchN, sSearchI;
int iSize, iStudent;
// Display initial vector size
iSize = vName.size();
cout << "Student list starts with the size:" << iSize << endl;
// Get size of list from user
cout << "How many students would you like to add?" << endl;
cin >> iStudent;
cin.ignore();
// Get names, ids, and classes
for (int i = 0; i < iStudent; i++)
{
cout << "Student" << i + 1 << ":\n";
cout << "Please enter the student name: ";
getline(cin, sName);
vName.push_back(sName);
cout << "Enter ID number ";
getline(cin, sID);
vID.push_back(sID);
cout << "Enter class name ";
getline(cin, sClass);
vClass.push_back(sClass);
}
// Display header
cout << "The list of students has the size of: " << iStudent << endl;
cout << "The Student List" << endl;
cout << "\n";
cout << "Name:" << setw(30) << "ID:" << setw(38) << "Enrolled Class : " << endl;
cout << "--------------------------------------------------------------------------";
cout << "\n";
// for loop for displying list
for (int x = 0; x < vName.size() && vID.size() && vClass.size(); x++)
{
cout << vName[x] << "\t \t \t" << vID[x] << "\t \t \t" << vClass[x] << endl;
}
// Sorting function and for loop to display sorted names
cout << "\n";
cout << "The Student List after Sorting:" << endl;
cout << "\n";
//*************************************
int startScan, minIndex;
for (startScan = 0; startScan < vName.size() - 1; startScan++)
{
minIndex = startScan;
minValue = vName[startScan];
for (int index = startScan + 1; index < vName.size(); index++)
{
if (vName[index] < minValue)
{
minValue = vName[index];
minIndex = index;
}
}
vName[minIndex] = vName[startScan];
vName[startScan] = minValue;
vID[minIndex] = vID[startScan];
vID[startScan] = minValue;
vClass[minIndex] = vClass[startScan];
vClass[startScan] = minValue;
}
//******************
//sort(vName.begin(), vName.end());
//for (int y = 0; y < vName.size(); y++)
//{
// cout << vName[y] << endl;
//}
cout << "\n";
// Search function uses a do while loop that loops so long as the user inputs a "y" or "Y"
do
{
int iPick;
cout << "Search Menu:" << endl;
cout << "1. By Name\n";
cout << "2. By ID\n \n";
cin >> iPick;
if (iPick == 1)
{
cout << "Please Enter a name to be searched:" << endl;
getline(cin >> ws, sSearchN);
if (binary_search(vName.begin(), vName.end(), sSearchN))
{
cout << sSearchN << " was found." << endl << endl;
}
else
{
cout << sSearchN << " was not found." << endl << endl;
}
cout << "Would you like to search another name?" << endl << endl;
cout << vName[0];
cout << "Please enter Y for Yes and N for No:" << endl << endl;
getline(cin >> ws, sQuestion);
}
else
{
cout << "Please Enter an ID to be searched:" << endl;
getline(cin >> ws, sSearchI);
if (binary_search(vID.begin(), vID.end(), sSearchI))
{
cout << sSearchI << " " << "was found" << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
getline(cin >> ws, sQuestion);
}
else
{
cout << sSearchI << " " << "was not found." << endl << endl;
cout << "Please enter Y for Yes and N for No:" << endl << endl;
getline(cin >> ws, sQuestion);
}
}
} while (sQuestion == "Y" || sQuestion == "y");
cout << "Thank you for using this program!" << endl;
return 0;
}
EDIT: posted whole program
So the issue is it doesn't sort at all, just gives back vName unsorted.
Okay upon more further study of the code I think I've figured it out.
So looking at the part of the code that is sorting, the way that it works is actually pretty simple. startScan is an int increments until it becomes equal to the size of the vector in the for loop. In this case it is vName. minIndex will hold the smallest index number which at the time of initialization will be equal to the starScan. Finally minValue is a string (in this case because we have a vector of strings) that acts as a temporary container for the element at vName[scanStart]. In the second for loop index will be incremented through the vector and will test if the element vName[index] is smaller than the temproray container i talked about earlier. If it is than the new temp will be vName[index] after that is done it will exit the inner loop and update and move on to the next smallest value in vName. Understanding this it's easy to make it so that the sorting happens with 2 other vectors. All one has to do is create containers for those vectors like the ones i have here minValueA and minValueB. They will simply be changing as vName changes. That way everything stays in the order in which vName is ordered. I hope that helps someone!
int startScan, minIndex;
string minValue, minValueA, minValueB;
for (startScan = 0; startScan < vName.size() - 1; startScan++)
{
minIndex = startScan;
minValue = vName[startScan];
minValueA = vID[startScan];
minValueB = vClass[startScan];
for (int index = startScan + 1; index < vName.size(); index++)
{
if (vName[index] < minValue)
{
minValue = vName[index];
minValueA = vID[index];
minValueB = vClass[index];
minIndex = index;
}
}
vName[minIndex] = vName[startScan];
vName[startScan] = minValue; //values for vName are being added to the other ones.
vID[minIndex] = vID[startScan];
vID[startScan] = minValueA;
vClass[minIndex] = vClass[startScan];
vClass[startScan] = minValueB;
}
//******************
sort(vName.begin(), vName.end());
for (int y = 0; y < vName.size(); y++)
{
cout << vName[y] << "\t \t \t " << vID[y] << "\t \t \t " << vClass[y] << endl;
}

Score component in beginner C++ program

I am doing an assignment where I am supposed to write a program to test the user's math skills. Here's the code i have right now:
using namespace std;
void addition()
{
int Value, Value2, Answer;
bool gotAnswer;
for (int i=1; i<=10; i++)
{
Value = 1 + (rand()%10);
Value2 = 1 + (rand()%10);
gotAnswer = false;
cout << Value << " + " << Value2 << " = ";
for (int a=1; (a<=3 && gotAnswer==false); a++)
{
cin >> Answer;
if (Answer==(Value+Value2))
{
cout << "CORRECT" << endl << endl;
gotAnswer = true;
}
else
{
cout << "WRONG Try again." << endl;
if (a==3)
{
cout << "You have missed 3 times. The answer is " << Value+Value2 << "." << endl << endl;
}
}
}
}
}
void substraction()
{
int Value, Value2, Answer;
bool gotAnswer;
for (int i=1; i<=10; i++)
{
Value = 1 + (rand()%10);
Value2 = 1 + (rand()%10);
gotAnswer = false;
cout << Value << " - " << Value2 << " = ";
for (int a=1; (a<=3 && gotAnswer==false); a++)
{
cin >> Answer;
if (Answer==(Value-Value2))
{
cout << "CORRECT" << endl << endl;
gotAnswer = true;
}
else
{
cout << "WRONG Try again." << endl;
if (a==3)
{
cout << "You have missed 3 times. The answer is " << Value-Value2 << "." << endl << endl;
}
}
}
}
}
void Multiplication()
{
int Value, Value2, Answer;
bool gotAnswer;
for (int i=1; i<=10; i++)
{
Value = 1 + (rand()%10);
Value2 = 1 + (rand()%10);
gotAnswer = false;
cout << Value << " x " << Value2 << " = ";
for (int a=1; (a<=3 && gotAnswer==false); a++)
{
cin >> Answer;
if (Answer==(Value*Value2))
{
cout << "CORRECT" << endl << endl;
gotAnswer = true;
}
else
{
cout << "WRONG Try again." << endl;
if (a==3)
{
cout << "You have missed 3 times. The answer is " << Value*Value2 << "." << endl << endl;
}
}
}
}
}
int main()
{
int number;
cout << "Enter the number for the problem type desired:"<<endl;
cout << " 1. Addition"<<endl;
cout << " 2. Subtraction"<<endl;
cout << " 3. Multiplication"<<endl;
cin >> number;
if (number == 1)
{
addition();
}
else if(number == 2)
{
substraction();
}
else if (number ==3)
{
Multiplication();
}
}
The program runs fine. However, there should be a score component where the user gets 10 points on the first try, 5 point on second try, and 0 on third try/wrong. I have no idea how to blend the score component in and the display at the end of 10 questions. Hints please?
All thanks in advance.
You should keep a score variable in each of your functions, add to the score variable as necessary and then return the score variable.
So those function are no longer going to be voids, they'll be ints. You can then get the score at the end and print it out.
I'm not going to write any code for you, since it is for an assignment :P