My function skips a loop parameter in c++ - c++

My GetMark() function, which is supposed to check for correct range and afterwards return the value, if correct to the given array gets stuck in a infinite loop when a parameter is given outside of the accepted range, before i added the SearchMark() function it worked correctly and looped only until the user finally entered a value in the given range (0 - 100) but now after the first out of range value is given it loops no matter what is entered, I will be thankful for any suggestions. full code:
int GetMark(int ModuleIndex) //user input function
{
bool help;
if (ModuleIndex < 0 || ModuleIndex >100)
{
help = false;
while (help != true)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "hey, that's a invalid value, try again!" << endl;
GetMark(ModuleIndex);
if ((ModuleIndex > 0) &&( ModuleIndex < 101))
{
help = true;
}
}
}
return ModuleIndex;
}
int SearchMark(int A[], int a) //search grades array for numbers of specific grades
{
int i = 0;
int ii = 0;
while (i < 12)
{
if (A[i] == a)
ii++;
i++;
}
cout << "Mark " << a << " was found: " << ii << " times" << endl;
return 0;
}
int main()
{
int marks[12];
int i = 0;
int sum = 0;
int grades[12];
while (i < 12)
{
cout << "enter mark (0 - 100): " << endl;
cin >> marks[i];
GetMark(marks[i]);
sum = sum + marks[i];
if (marks[i] > 69)
{
grades[i] = 1;
}
else if (marks[i] > 59 && marks[i] < 70)
{
grades[i] = 2;
}
else if (marks[i] > 49 && marks[i] < 60)
{
grades[i] = 22;
}
else if (marks[i] > 39 && marks[i < 50])
{
grades[i] = 3;
}
else if (marks[i] < 35)
{
grades[i] = 4;
}
i++;
}
sum = sum / 12;
cout << "your average is: " << sum << endl;
if (sum > 69)
{
cout << "You passed with 1st!" << endl;
}
else if ((sum > 59) && (sum < 70))
{
cout << "You passed with 2i!" << endl;
}
else if ((sum > 49) && (sum < 60))
{
cout << "You passed with 2ii!" << endl;
}
else if ((sum > 39) && (sum < 50))
{
cout << "You passed with 3rd!" << endl;
}
else if (sum < 40)
{
cout << "Your average is too low! You failed." << endl;
}
i = 0;
while (i < 12)
{
if (marks[i] < 35)
{
cout << "Referred in module " << i + 1 << " mark too low." << endl;
}
i++;
}
SearchMark(grades, 1);
SearchMark(grades, 2);
SearchMark(grades, 22);
SearchMark(grades, 3);
SearchMark(grades, 4);
return 0;
}`

That function is overly complicated for what it does. Just loop while the value is bad, and prompt for a new value:
int GetMark(int ModuleIndex) {
while (ModuleIndex < 0 || ModuleIndex > 100) {
std::cout << "Invalid value.\n"
std::cin >> ModuleIndex;
}
return ModuleIndex;
}
Recursion is very handy in theoretical analysis, but in practice it's almost always a mistake.

You need to allow the user to specify a new value of marks[i] / ModuleIndex within GetMarks. After clearing cin, read a new value from cin. You also need to return that value so that main's marks[i] can be updated with that value instead of the original out-of-range value.

Basically what you need to do is remove the recursion from this method and just rely on the while loop. Instead of recalling the function you need to prompt for input again with the failed input and then test the value again to escape the loop.
int GetMark(int ModuleIndex) //user input function
{
bool help;
if (ModuleIndex < 0 || ModuleIndex >100)
{
help = false;
while (help != true)
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "hey, that's a invalid value, try again!" << endl;
cout << "enter mark (0 - 100): " << endl;
cin >> ModuleIndex;
if ((ModuleIndex > 0) &&( ModuleIndex < 101))
{
help = true;
}
}
}
return ModuleIndex;
}

It is apparently in you getMark, inside the while loop you are calling getMark recursively with the same invalid ModuleIndex value. So you need to get it from the standard input before recursion. e.g:
int GetMark(int ModuleIndex){
bool help;
if (ModuleIndex < 0 || ModuleIndex > 100){
help = false;
while (help != true){
cout << "enter new ModuleIndex: \n";
cin >> ModuleIndex;
GetMark(ModuleIndex);
// ...
}
return ModuleIndex;
}
Your code is unreadable, in addition you can use class std::vector.
I propose to test this code:
int GetMarkIndex(const std::vector<double>& vMarks, const double Search) {
auto beg{ vMarks.begin() }, end{ vMarks.end() };
while (beg != end && *beg != Search)
++beg;
return beg != end ? beg - vMarks.begin() : -1;
}
int main() {
std::vector<double> marks(5);
int value;
auto i{ 0U };
auto sz{ marks.size() };
while (i != sz) {
std::cout << "Enter marks 1-->100" << std::endl;
if (cin >> value && value > 0 && value < 101) {
marks[i] = value;
++i;
}
else
std::cout << "Invalid input!" << std::endl;
}
for (auto e : marks)
cout << e << ", ";
std::cout << std::endl;
double Search = 15;
auto index{GetMarkIndex(marks, Search)};
(index != -1) ? (std::cout << Search << " Found at index: " << index) : (std::cout << Search << " Not found!" << std::endl);
std::cout << std::endl;
}

The combination of the way you have defined GetMark and the way you use it is flawed.
No matter what you do in GetMark, the value entered in main does not change.
Change GetMark to:
int GetMark()
{
std::cout << "enter mark (0 - 100): " << std::endl;
int mark;
while ( std::cin >> mark )
{
if ( mark >= 0 && mark <= 100)
{
return mark;
}
std::cout << "Invalid value " << mark << std::endl;
std::cout << "enter mark (0 - 100): " << std::endl;
}
// Unable to read.
// Throw exception, or exit with an error message.
}
and change its usage. Instead of
cout << "enter mark (0 - 100): " << endl;
cin >> marks[i];
GetMark(marks[i]);
use
marks[i] = GetMark();
A working version of GetMark:
int GetMark()
{
std::cout << "enter mark (0 - 100): " << std::endl;
std::string line;
while ( getline(std::cin, line) )
{
std::istringstream str(line);
int mark;
if ( str >> mark )
{
if ( mark >= 0 && mark <= 100)
{
return mark;
}
}
std::cout << "Invalid input: " << line << std::endl;
std::cout << "enter mark (0 - 100): " << std::endl;
}
// Unable to read.
// Throw exception, or exit with an error message.
return 0;
}
Live Demo.

Related

How can I print the trash value as the correct value?

I pressed 1 and entered information related to students. Then press 2 to get the calculations that fit the information I entered, but the trash values come out.
#include <iostream>
#include <cstring>
using namespace std;
struct Subject { //과목 정보
char Subname[30]; //과목이름
int Hakjum; //과목학점
char Grade[10]; //과목등급
float GPA; //과목평점
};
struct Student { //학생정보
char StdName[30]; //학생이름
int Hakbun; //학번
Subject Sub[3]; //과목
float AveGPA; //교과목 평균 평점
};
int main()
{
cout.precision(2);
cout << fixed;
int n = 0;
struct Student Stu[10]; //구조체변수 선언
while (n < 3) //반복문을 통해 1또는 2를 눌렀을 때 메뉴판으로 돌아오기
{
cout << "===== 메뉴 =====\n"; //메뉴판
cout << "1. 학생 성적 입력\n";
cout << "2. 전체 학생 성적 보기\n";
cout << "3. 프로그램 종료\n";
cout << "\n";
cout << "원하는 기능을 입력하세요 : ";
cin >> n;
if (n <= 1) { //1번 선택하였을 경우
for (int t = 0; t <= 1; t++)
{
cout << "*" << t + 1 << " 번째 학생 이름과 학번을 입력하세요.\n"; //이름과 학번을 입력 받음
cout << "이름 : ";
cin >> Stu[t].StdName;
cout << "학번 : ";
cin >> Stu[t].Hakbun;
cout << "\n";
cout << "\n";
cout << "* 수강한 과목3개와 각 교과목명, 과목학점, 과목등급을 입력하세요.\n"; //과목과, 학점, 등급을 입력받음
for (int a = 0; a < 3; a++)
{
cout << "교과목명 : ";
cin >> Stu[t].Sub[a].Subname;
cout << "과목학점수 : ";
cin >> Stu[t].Sub[a].Hakjum;
cout << "과목등급<A+ ~ F> : ";
cin >> Stu[t].Sub[a].Grade;
cout << "\n";
}
cout << "\n\n\n";
}
}
else if (n <= 2) { //2번 선택하였을 경우
cout << "\n\t\t전체 학생 성적 보기\n";
cout << "===================================================================\n";
for (int t = 0; t <= 1; t++) {
cout << "이름 : " << Stu[t].StdName << "\t학번 : " << Stu[t].Hakbun << "\n"; //학생의 개인정보 출력
cout << "===================================================================\n";
cout << "\t\t과목명 \t 과목학점 \t과목등급 \t과목평점\n";
cout << "===================================================================\n";
for (int a = 0; a < 3; a++) { //문자열 비교 연산자를 사용하여 등급을 평점으로 바꿈
if (Stu[t].Sub[a].Grade, "A+" == 0) {
Stu[t].Sub[a].GPA = 4.5 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "A0" == 0) {
Stu[t].Sub[a].GPA = 4.0 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "B+" == 0) {
Stu[t].Sub[a].GPA = 3.5 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "B0" == 0) {
Stu[t].Sub[a].GPA = 3.0 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "C+" == 0) {
Stu[t].Sub[a].GPA = 2.5 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "C0" == 0) {
Stu[t].Sub[a].GPA = 2.0 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "D+" == 0) {
Stu[t].Sub[a].GPA = 1.5 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "D0" == 0) {
Stu[t].Sub[a].GPA = 1.0 * Stu[t].Sub[a].Hakjum;
}
else if (Stu[t].Sub[a].Grade, "F" == 0) {
Stu[t].Sub[a].GPA = 0.0 * Stu[t].Sub[a].Hakjum;
}
Stu[t].AveGPA = (Stu[t].Sub[0].GPA + Stu[t].Sub[1].GPA + Stu[t].Sub[2].GPA) / (Stu[t].Sub[0].Hakjum + Stu[t].Sub[1].Hakjum + Stu[t].Sub[2].Hakjum); //평균 평점을 구함
cout << "\t\t" << Stu[t].Sub[a].Subname << "\t\t" << Stu[t].Sub[a].Hakjum << "\t " << Stu[t].Sub[a].Grade << "\t\t " << Stu[t].Sub[a].GPA << "\n"; //과목명, 과목학점, 과목등급, 과목평점 출력
}
cout << "===================================================================\n";
cout << "\t\t\t\t평균평점\t" << Stu[t].AveGPA << "\n\n";
}
}
}
return 0;
}
The output
enter image description here
I get a trash value in the "subject grade".
Expected
I want it to be calculated according to the number I enter.
I hope the "과목평점" is right.
This is garbage:
if (Stu[t].Sub[a].Grade, "A+" == 0) {
What it does is use comma operator. So first it will get Stu[t].Sub[a].Grade and... do nothing with it. Then it will get "A+" == 0, which is comparing string literal (const char* pointer) to 0, which is same as nullptr, which is false because string literal is not going to be nullptr. So this condition is always false. It's the last experssion with the comman operator, so this false result will be used for the if. Same for the rest of them.
It should be
if (std::strcmp(Stu[t].Sub[a].Grade, "A+") == 0) {
The function std::strcmp is declared in cstring header, which you already have included, and since you have using namespace std there, you can leave the std:: out if you feel confident you know std:: namespace functions well enough.

C++ Program leaving my for loop prematurely

I'm working on a little poker application and i've run into the first problem I just can't seem to comprehend.
while (allplayersGood != 1) { //round table till all decided
cout << "TOP OF WHILE LOOP";
for (int i = 0; i < PLAYER_COUNT; i++) { //for loop for decisions from non button or blinds
int player_decision = 1;
char choice;
if ((players[i].playerhand.card1.value != 'F') && (players[i].playerhand.card1.value != 'C')) {
if ((players[i].blind != 1 && players[i].blind != 2) && players[i].button != true) {
cout << "\n\n";
cout << " POT: " << playerTable->currentPot;
cout << "\n";
for (int i = 0; i < PLAYER_COUNT; i++) {
cout << "Player " << players[i].playernumber;
cout << " (" << players[i].chip_amount << ") ";
}
while (player_decision == 1) {
if (playerTable->currentBet > players[i].currentBet) {
cout << "\n\nPlayer " << players[i].playernumber << " ("; players[i].playerhand.printhand(); cout << ") " << "Type F for Fold, B for Call, R for Raise: ";
cin >> choice;
players[i].choice = choice;
if (choice == 'F') {
player_decision = 0;
players[i].fold();
}
if (choice == 'R') {
player_decision = 0;
players[i].bet(playerTable);
}
if (choice == 'B') {
player_decision = 0;
players[i].call(playerTable);
}
}
if ((playerTable->currentBet == players[i].currentBet) && player_decision != 0) { //big blind after round table
cout << "\n\nPlayer " << players[i].playernumber << " ("; players[i].playerhand.printhand(); cout << ") " << "Type C for Check, R for Raise: ";
cin >> choice;
players[i].choice = choice;
if (choice == 'B') {
player_decision = 0;
players[i].bet(playerTable);
}
if (choice == 'C') {
if (players[i].check(playerTable) == true) {
player_decision = 0;
}
}
}
}
}
else if (players[i].blind == 1 || players[i].blind == 2) {
if (players[i].blind == 1) {
players[i].chip_amount -= sblind;
playerTable->currentPot += sblind;
players[i].blind = 0;
players[i].currentBet = sblind;
}
if (players[i].blind == 2) {
players[i].chip_amount -= bblind;
playerTable->currentPot += bblind;
players[i].blind = 0;
players[i].currentBet = bblind;
}
}
}
}
for (int i = 0; i < PLAYER_COUNT; i++) { //seperate loop for button and blinds that were ignored in loop above
int player_decision = 1;
char choice;
if (players[i].button == true || players[i].blind == 1) { //button and small blind
cout << "\n\n";
cout << " POT: " << playerTable->currentPot;
cout << "\n";
for (int i = 0; i < PLAYER_COUNT; i++) {
cout << "Player " << players[i].playernumber;
cout << " (" << players[i].chip_amount << ") ";
}
while (player_decision == 1) {
cout << "\n\nPlayer " << players[i].playernumber << " ("; players[i].playerhand.printhand(); cout << ") " << "Type F for Fold, B for Call, R for Raise: ";
cin >> choice;
players[i].choice = choice;
if (choice == 'F') {
player_decision = 0;
players[i].fold();
}
if (choice == 'R') {
player_decision = 0;
players[i].bet(playerTable);
}
if (choice == 'B') {
player_decision = 0;
players[i].call(playerTable);
}
}
}
cout << i;
if (players[i].blind == 2) { //big blind
cout << "\n\n";
cout << " POT: " << playerTable->currentPot;
cout << "\n";
for (int i = 0; i < PLAYER_COUNT; i++) {
cout << "Player " << players[i].playernumber;
cout << " (" << players[i].chip_amount << ") ";
}
while (player_decision == 1) {
cout << "\n\nPlayer " << players[i].playernumber << " ("; players[i].playerhand.printhand(); cout << ") " << "C for Check, R for Raise: ";
cin >> choice;
players[i].choice = choice;
if (choice == 'C') {
if (players[i].check(playerTable) == true) {
player_decision = 0;
}
}
if (choice == 'R') {
player_decision = 0;
players[i].bet(playerTable);
}
}
}
}
int playersBetting = 0;
int playersGood = 0;
int playersChecked = 0;
int playersNot = 0;
for (int i = 0; i < PLAYER_COUNT; i++) {
if (players[i].playerhand.card1.value != 'F') {
playersBetting++;
if (players[i].currentBet == playerTable->currentBet) {
playersGood++;
}
}
}
for (int i = 0; i < PLAYER_COUNT; i++) {
if (players[i].playerhand.card1.value != 'F') {
if (players[i].isChecked == true) {
playersChecked++;
}
else {
playersNot++;
}
}
}
cout << playersBetting << playersGood;
if ((playersBetting == playersGood) || (playersNot == 0)) {
cout << "NEXT ROUND STARTED";
}
}
The issue is, during the second for loop with comment "seperate loop for button and blinds that were ignored in loop above" after the first if statement succeeds because players[0] has button equal to true, the player will make the terminal input as a decision, and the program will exit the for loop and go down to the end with the playersBetting and playersGood loops, then return back to the for loop at index 1 correctly.
I'm sorry if this is a little complicated to understand there is a lot of code that I probably didn't put into context very well, if you need any extra information please let me know.
Thank you.
You seem to have different loops inside one another. This is possible, but in that case, you need to use another loop variable (j instead of i), let me show you what happens:
for i ...
for j ...
This causes the following values to be taken for i and j:
i j
1 1
1 2
1 ...
1 n
2 1
2 2
2 ...
2 n
...
n 1
n 2
...
n n
... and here it stops.
If you keep using i in the inner loop, this is what you get:
i (outside loop) i (inside loop)
1 1
2 2 // indeed: changing i inside also changes i outside
... ...
n n
So you jump out of the outside loop, even after just having looped the inside loop one time.
I figured it out, it was unrelated to the actual loop and actually had to do with a value I changed upstream. Thank you for the few who tried to help with such little context haha
Have a good one

Getting values from dynamic struct array

I trying to create a program that receives and stores information about in a dynamic array of structures. And the program should sort and display the teams above average, average and below avaerage. This is my code so far. . So what I'm doing is I receive the user input the check the input before storing it in dynamic structure array. Then finally I display all the information stored in the struct. Here's the output that i'm currently getting and I'm not sure why i'm getting this negative numbers.any ideas why?
Thanks
How many teams do you want to store? 2
Enter the name of the team 1:Vikings
Enter the team 1 percentage: 90
Enter the name of the team 2:PackersGreen Bay Packers
Enter the team 2 percentage: 80
Above Average :
Vikings 90%
PackersGreen Bay Packers 80%
Average :
5.00136e-317%
None
Below Average :
None
9.25737e-306%
Here's my code.
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
struct aboveAverage
{
string name9;
double percentage1;
};
struct average
{
string name10;
double percentage2;
};
struct belowAverage
{
string name11;
double percentage3;
};
int numOfteams;
double userInput;
cout << "How many teams do you want to store? ";
cin >> numOfteams;
cin.get();
aboveAverage * arrayOfAboveAverage = new aboveAverage[numOfteams];
average * arrayOfAverage = new average[numOfteams];
belowAverage * arrayOfbelowAverage = new belowAverage[numOfteams];
for (int i = 0; i < numOfteams; i++)
{
start:
int x = i + 1;
string name5;
cout << "Enter the name of the team " << x << ":";
getline(cin, name5);
cout << "Enter the team " << x << " percentage: ";
cin >> userInput;
cin.get();
if (userInput >= 66 && userInput <= 100)
{
arrayOfAboveAverage[i].percentage1 = userInput;
arrayOfAboveAverage[i].name9 = name5;
}
else if (userInput <= 66 && userInput >= 33)
{
arrayOfAverage[i].name10 = name5;
arrayOfAverage[i].percentage2 = userInput;
}
else if (userInput <= 33 && userInput >= 0)
{
arrayOfbelowAverage[i].name11 = name5;
arrayOfbelowAverage[i].percentage3 = userInput;
}
else
{
cout << "Percent cannot be greater than 100" << endl;
goto start;
}
}
cout << "Above Average :" << endl;
for (int j = 0; j < numOfteams; j++)
{
if (arrayOfAboveAverage[j].percentage1 != NULL ||
arrayOfAboveAverage[j].name9 != "")
{
cout << arrayOfAboveAverage[j].name9 <<" ";
cout << arrayOfAboveAverage[j].percentage1 <<"%"<< endl;
}
else
{
cout << "None" << endl;
}
}
cout << "Average :" << endl;
for (int j = 0; j < numOfteams; j++)
{
if (arrayOfAverage[j].percentage2 > 0 ||
arrayOfAverage[j].name10 != "")
{
cout << arrayOfAverage[j].name10 <<" ";
cout << arrayOfAverage[j].percentage2 <<"%"<<endl;
}
else
{
cout << "None" << endl;
}
}
cout << "Below Average : "<< endl;
for (int k = 0; k < numOfteams; k++)
{
if (arrayOfbelowAverage[k].percentage3 > 0 ||
arrayOfbelowAverage[k].name11 != "")
{
cout << arrayOfbelowAverage[k].name11 << " ";
cout << arrayOfbelowAverage[k].percentage3 <<"%"<< endl;
}
else
{
cout << "None" << endl;
}
}
delete[] arrayOfAboveAverage;
delete[] arrayOfAverage;
delete[] arrayOfbelowAverage;
return 0;
}
The problem is in the following test
if (arrayOfAverage[j].percentage2 > 0 ||
arrayOfAverage[j].name10 != "")
When arrayOfAverage is uninitialized (as in your case) name10 is initialized with the default value for a std::string (the empty string) but the value for percentage2 (a double) is undefined.
You test both values with "or", not "and", so if percentage2 is initialized with a positive value (by example: 5.00136e-317) you enter in the true case.
Suggestion: when there is a useful value, the name10 value isn't empty, so ignore percentage2 and modify the test as follows
if ( ! arrayOfAverage[j].name10.empty() )
Same problem with the preceding
if (arrayOfAboveAverage[j].percentage1 != NULL ||
arrayOfAboveAverage[j].name9 != "")
and the following test
if (arrayOfbelowAverage[k].percentage3 > 0 ||
arrayOfbelowAverage[k].name11 != "")
My suggestion is to modify they as follows
if ( ! arrayOfAboveAverage[j].name9.empty() )
// ...
if ( ! arrayOfBelowAverage[j].name11.empty() )

Counter adding items to array with remainder

I am creating an RPG shop. It must have items, gold, and item price. Essentially creating an inventory. What i am trying to accomplish is, where the players gold is 0 they cannot add any more items to their inventory, and cannot have negative gold.
When running my code in debug mode it appears to be doing what i want, but when the function exits the amount the player requested has not been countered.
Keep in mind i am still new to c++.
Thanks
#include <iostream>
#include <string>
using namespace std;
// Global consts
const int numItems = 4;
const string items[numItems] = {"boots", "hats", "cats", "bats"}; // create string array of numItems items.
// Create stuct, that holds:
// Item, gold, price.
struct Inv {
int pInv[numItems] = {0, 0, 0, 0};
int gold = 100;
int itemPrice[numItems] = { 10, 6, 12, 15 };
}inv;
void iniItems();
void printItems();
bool buyItems();
bool sellItems();
int main() {
bool isDone = false;
iniItems();
while (isDone == false) {
printItems();
int choice;
bool x = false;
cout << "\nWhat would you like to do? Enter (" << 1 << "-" << 2 << "): " << endl;
cout << "1: Buy Items. \n2: Sell Items." << endl; cin >> choice; cout << endl;
while (x == false) {
if (choice == 1) {
x = buyItems();
}
if (choice == 2) {
x = sellItems();
}
}
}
system("pause");
// dynamic memory not implemented yet. Must wait for working fix of shoppe.cpp
}
void iniItems() {
cout << "** Shop Inventory: **" << endl;
for (int i = 0; i < numItems; i++) {
cout << i + 1 << " - " << items[i] << " - price: $" << inv.itemPrice[i] << endl;
}
}
void printItems() {
cout << "\n** Player Inventory: **" << endl;
cout << "Gold: $" << inv.gold << endl;
for (int i = 0; i < numItems; i++) {
cout << inv.pInv[i] << " x " << items[i] << endl;
}
}
bool buyItems() {
bool exit = false;
int amount;
const int remainder = 10;
printItems();
cout << "\nEnter -1 to quit." << endl;
cout << "What would you like to buy? Enter (" << 1 << "-" << 4 << "): " << endl;
// Get item info.
while (exit == false) {
int inp;
cout << "Item: "; cin >> inp; cout << endl;
cout << "Amount: "; cin >> amount; cout << endl;
// Check if input is valid.
if (inp > 0 && inp <= numItems) {
if (amount >= 0) {
inv.pInv[inp - 1] = 1 * amount;
inv.gold = inv.itemPrice[inp - 1] / amount;
}
// If gold is 0, make sure the user cannot gain more items.
if (inv.gold <= 0) {
int tmp;
inv.gold = 0;
tmp = remainder - amount;
for (int i = tmp; i >= 0; i++) {
inv.pInv[inp - 1]--;
}
return inv.pInv[inp - 1];
}
if (inp == -1) {
return true;
}
if (inp > numItems) {
cout << "Enter valid number." << endl;
return false;
}
else return false;
}
}
if (exit == true) {
return true;
}
}
So i limited the code down into a do while loop with a counter for the gold, in the buyItems() function.
Here it is, if anyone is interested.
do {
inv.gold -= inv.itemPrice[inp - 1];
++(inv.pInv[inp - 1]);
} while (inv.gold > 0);
if (inv.gold < 0) {
inv.gold = 0;
inv.pInv[inp - 1]--;
}
printItems();

vector iterator + offset out of range, at the end of while loop it gives the error

while (deckSize > 2)
{
one_Card = card_deck.back();
card_deck.pop_back();
two_Card = card_deck.back();
card_deck.pop_back();
three_Card = card_deck.back();
card_deck.pop_back();
oneCard_Name = card_name(one_Card);
twoCard_Name = card_name(two_Card);
threeCard_Name = card_name(three_Card);
oneCard_Suit = card_suit(one_Card);
twoCard_Suit = card_suit(two_Card);
threeCard_Suit = card_suit(three_Card);
oneCard_Rank = card_rank(one_Card);
twoCard_Rank = card_rank(two_Card);
threeCard_Rank = card_rank(three_Card);
bool between1 = (oneCard_Rank < threeCard_Rank && threeCard_Rank < twoCard_Rank);
bool between2 = (twoCard_Rank < threeCard_Rank && threeCard_Rank < oneCard_Rank);
cout << "Here are your two cards: " << endl;
cout << setw(10) << oneCard_Name << " of " << oneCard_Suit << setw(20) << twoCard_Name << " of " << twoCard_Suit << endl;
cout << "Do you think the next card will lie between these? (y/n): ";
cin >> user_input;
cout << endl << endl;
cout << "Here is your next card: " << endl;
cout << setw(10) << threeCard_Name << " of " << threeCard_Suit << endl << endl << endl;
count++;
if(user_input == "y" || user_input == "yes" || user_input == "Yes" || user_input == "Y")
{
if(between1 || between2)
{
cout << "You win!" << endl;
win++;
}
else
{
cout << "You lose!" << endl;
lose++;
}
}
else
{
if(between1 || between2)
{
cout << "You lose!" << endl;
lose++;
}
else
{
cout << "You win!" << endl;
win++;
}
}
}
cout << "You have played this game " << count << " times and you have won: " << win << " and lost " << lose << endl;
return 0;
}
These are the two subprograms that shuffle and initialize the deck
void initDeck(vector<int> &card_deck)
{
int i;
for(i = 0; i <= 51; i++)
{
card_deck[i] = i;
}
}
void shuffleDeck(vector<int> & card_deck)
{
int n;
for(n = 51; n >= 0; n--)
{
int i = randomize();
int temp = card_deck[i];
int temp2= card_deck[n];
card_deck[n] = temp;
card_deck[i] = temp2;
}
}
After when I run the program it allows me to run it, but when I reach to the number less than the condition in the while loop it just gives me an error, and does not finish the program. I had this error earlier and fixed it, so I have a basic understanding of what the error means. From my knowledge it is trying to collect numbers past the vector length. However this time I don't see my error at all.
deckSize is not being set/updated anywhere. It should rather be card_deck.size()
You should use push_back and emplace for the type vector like this:
void initDeck(vector<int> &card_deck){
int i;
for(i = 0; i <= 51; i++)
{
card_deck.push_back(i);
}
}
Take a see to this link
Try this:
void initDeck(vector<int> &card_deck)
{
int i;
for(i = 0; i <= 51; i++)
{
card_deck.push_back(i);
}
}
void shuffleDeck(vector<int> & card_deck)
{
int n;
for(n = 51; n >= 0; n--)
{
int i = randomize();
int temp = card_deck[i];
int temp2= card_deck[n];
card_deck[n] = temp;
card_deck[i] = temp2;
}
}
For generating random number see this and this. Or you can find other solution that is more reliable.