Binary Search for String not working correctly - c++

The following program is an Inventory Menu. For some reason everything seems to work except when I searching for the name of the product (option 3) function lookupName. It was working before I put a condition to where if nothing was returned, to give an error message, which is the same I used for lookupSku and that one is working fine. I am not sure what is wrong with the code anymore.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
struct inventory {
string name;
int sku;
int quantity;
double price;
};
int size = 0;
void fillArray ( inventory[], int&, ifstream& );
void sortArray ( inventory[], int );
void displayIn ( inventory[], int );
int lookupSku ( inventory[], int, int );
int lookupName ( inventory[], int, string );
int main(){
// Constants for menu choices
const int DISPLAY_INVENTORY = 1,
LOOKUP_SKU = 2,
LOOKUP_NAME = 3,
QUIT_CHOICE = 4;
int choice;
inventory products [100];
ifstream fin;
fin.open ("inventory.dat");
if (!fin)
{
cout << endl << endl
<< " ***Program Terminated. *** " << endl << endl
<< " Input file failed to open. " << endl;
system ( "PAUSE>NUL" );
return 1;
}
fillArray ( products, size, fin );
sortArray ( products, size );
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(2);
do
{
// Display the menu.
cout << "\n\t\t Manage Inventory Menu\n\n"
<< "1. Display inventory sorted by sku\n"
<< "2. Lookup a product by sku\n"
<< "3. Lookup a product by name\n"
<< "4. Quit the Program\n\n"
<< "Enter your choice: ";
cin >> choice;
cout << endl;
// Validate the menu selection.
while (choice < DISPLAY_INVENTORY || choice > QUIT_CHOICE)
{
cout << "Please enter a valid menu choice: ";
cin >> choice;
}
// Validate and process the user's choice.
if (choice != QUIT_CHOICE)
{
int indexSku,
indexName,
skuChoice;
string nameChoice;
switch (choice)
{
case DISPLAY_INVENTORY:
displayIn ( products, size );
break;
case LOOKUP_SKU:
cout << "Enter the Sku number: ";
cin >> skuChoice;
cout << endl;
indexSku = lookupSku( products, size, skuChoice );
if ( indexSku >= 0 )
{
cout << "Product Name: " << products[indexSku].name << endl
<< "Sku: " << products[indexSku].sku << endl
<< "Quantity: " << products[indexSku].quantity << endl
<< "Price: " << products[indexSku].price << endl;
}
else
cout << "No product found with this sku!" << endl;
break;
case LOOKUP_NAME:
cout << "Enter product name with no spaces: ";
cin >> nameChoice;
cout << endl;
indexName = lookupName( products, size, nameChoice );
if ( indexName >= 0 )
{
cout << "Product Name: " << products[indexName].name << endl
<< "Sku: " << products[indexName].sku << endl
<< "Quantity: " << products[indexName].quantity << endl
<< "Price: " << products[indexName].price << endl;
}
else
cout << "No product found with this product name!" << endl;
break;
}
}
} while (choice != QUIT_CHOICE);
fin.close ();
return 0;
}
void fillArray ( inventory product[], int &size, ifstream &fin )
{
int counter = 0;
while (fin >> product[counter].name)
{
fin >> product[counter].sku>> product[counter].quantity
>> product[counter].price;
counter ++;
}
size = counter;
}
void sortArray ( inventory product[], int size )
{
bool swap;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if ( product[count].sku > product[count + 1].sku )
{
inventory temp = product[count];
product[count] = product[count + 1];
product[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
void displayIn ( inventory product[], int size )
{
for ( int i = 0; i < size; i++ )
cout << product[i].sku << " " << product[i].quantity << " "
<< product[i].price << " " << setw(4) << product[i].name << endl;
}
int lookupSku(inventory product[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (product[middle].sku == value)
{
found = true;
position = middle;
}
else if (product[middle].sku > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
int lookupName ( inventory product[], int size , string value )
{
int first = 0,
last = size - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (product[middle].name == value)
{
found = true;
position = middle;
}
else if (product[middle].name > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}

You code for looking up the product name using Binary Search is correct, but it appears that the data is sorted by SKU. The Binary Search algorithm will only work if the data is sorted.
You could modify your program to sort the data by product name before applying the Binary Search, but in this case since you are using a Bubble Sort which is an N^2 search time, you would be better off with just a linear search for the product name.

Related

How to define 'i' in a (I think) constant array and the sum in c++ with variables?

I keep on getting an error message about line 29, and that the 'i' in "individualCommission[i]" isn't defined. Also, I am trying to find the sum of the entire array.
#include <iostream>
#include <iomanip>
using namespace std;
void heading( string assighnmentName ); // prototype - declare the function
void dividerLine( int length, char symbol );
int main()
{
// assighnment heading
heading( "GPA Calculator" );
//create variables to hold user data and calculated data
double commissionRate = 0.00;
int salesNumber = 0;
cout << endl;
cout << "Hello there! How many sales did you make? ";
cin >> salesNumber;
if( salesNumber <= 0 )
{
cout << "Invalid entry - enter 1 or more, please" << endl;
}
// convert the salesNumber into a constant to use with our array structures & create array structures
const int arraySize = salesNumber;
string salesName[ arraySize ];
double salesAmount[ arraySize ];
double individualCommission[ arraySize ];
// collect input from user for arraySize
for ( int i = 0; i < arraySize; i++ )
{
cin.ignore( 256, '\n' ); // because it doesn't like the switches with cin to string
cout << "What is your #" << i + 1 << " sale labeled? ";
getline( cin, salesName[i] );
do
{
cout << "How much does " << salesName[i] << " cost? $ ";
cin >> salesAmount[i]; //pointing the location in the array
if( salesAmount[i] <= 0 )
{
// add this line to prevent keyboard buffer issues //
cout << "Invalid entry - input valure more than zero";
}
// the else if statments
if( salesAmount[i] <= 10000 )
{
commissionRate = .1;
}
else if( salesAmount[i] <= 15000 )
{
commissionRate = .15;
}
else if( salesAmount[i] > 15,000 )
{
commissionRate = .2;
}
}while( salesAmount[i] <= 0 );
}
individualCommission[i] = salesAmount[i] * commissionRate)[i];
dividerLine( 40, '-' );
for( int i = 0; i < arraySize; i++ )
{
cout << salesName[i];
cout << "\t\t\t";
cout << salesAmount[i];
cout << "\t\t\t";
cout << individualCommission[i];
cout << endl;
}
// This is what I need: comissionEarned = BLAH BLAH SOMETHING I DONT KNOW THE ANSWER TO
// cout << "Total Commission: " << setw(10) << setprecision(2) << fixed << "$ " << commissionEarned << endl;
dividerLine( 40, '-' );
cout << endl << "Thank you for using my commission calculator!";
return 0;
}
// DOMAIN OF MY FUNCTIONS //////////////////////////////////////////////////
void heading( string assighnmentName )
{
cout << endl << "Amelia Schmidt" << endl;
cout << "Mrs. Carr, Period 3" << endl;
cout << assighnmentName << endl;
cout << "November 8, 2022" << endl << endl;
dividerLine( 40, '-' );
}
void dividerLine( int length, char symbol )
{
for( int i = 0; i < length; i++ )
{
cout << symbol;
}
cout << endl;
} // end the function dividerLine(int, char)
This is the error message I keep getting.
I've tried some arr statements, but I honestly don't know what they actually do or if I'm writing the wrong statement. I have no clue how to work with the [i] undefined part.
Your code was simple to fix. You had put a statement outside the for and it couldn't save the data inside the array. The change was made in line 61:
#include <iostream>
#include <iomanip>
#include <numeric>
using namespace std;
void heading( string assighnmentName ); // prototype - declare the function
void dividerLine( int length, char symbol );
int main() {
// assighnment heading
heading( "GPA Calculator" );
//create variables to hold user data and calculated data
double commissionRate = 0.00;
int salesNumber = 0;
cout << endl;
cout << "Hello there! How many sales did you make? ";
cin >> salesNumber;
if( salesNumber <= 0 ) {
cout << "Invalid entry - enter 1 or more, please" << endl;
}
// convert the salesNumber into a constant to use with our array structures & create array structures
const int arraySize = salesNumber;
string salesName[ arraySize ];
double salesAmount[ arraySize ];
double individualCommission[ arraySize ];
// collect input from user for arraySize
for ( int i = 0; i < arraySize; i++ ) {
cin.ignore( 256, '\n' ); // because it doesn't like the switches with cin to string
cout << "What is your #" << i + 1 << " sale labeled? ";
getline( cin, salesName[i] );
do {
cout << "How much does " << salesName[i] << " cost? $ ";
cin >> salesAmount[i]; //pointing the location in the array
if( salesAmount[i] <= 0 ) {
// add this line to prevent keyboard buffer issues //
cout << "Invalid entry - input valure more than zero";
}
// the else if statments
if( salesAmount[i] <= 10000 ) {
commissionRate = .1;
}
else if( salesAmount[i] <= 15000 ) {
commissionRate = .15;
}
else if( salesAmount[i] > 15,000 ) {
commissionRate = .2;
}
} while( salesAmount[i] <= 0 );
individualCommission[i] = salesAmount[i] * commissionRate;
}
dividerLine( 40, '-' );
for( int i = 0; i < arraySize; i++ ) {
cout << salesName[i];
cout << "\t\t\t";
cout << salesAmount[i];
cout << "\t\t\t";
cout << individualCommission[i];
cout << endl;
}
double comissionEarned = accumulate(individualCommission, individualCommission+arraySize, 0);
cout << "Total Commission: " << setw(10) << setprecision(2) << fixed << "$ " << comissionEarned << endl;
dividerLine( 40, '-' );
cout << endl << "Thank you for using my commission calculator!";
return 0;
}
// DOMAIN OF MY FUNCTIONS //////////////////////////////////////////////////
void heading( string assighnmentName ) {
cout << endl << "Amelia Schmidt" << endl;
cout << "Mrs. Carr, Period 3" << endl;
cout << assighnmentName << endl;
cout << "November 8, 2022" << endl << endl;
dividerLine( 40, '-' );
}
void dividerLine( int length, char symbol ) {
for( int i = 0; i < length; i++ ) {
cout << symbol;
}
cout << endl;
} // end the function dividerLine(int, char)
However I would recommend giving you a couple of tips about the code.
First, always try to understand where the problem lies and don't post hundreds of badly formatted lines of code. Even just a minimum of reproducible code is enough. This also allows us to focus more on the error without thinking about what your program is really doing.
Also, in the current C++ standard, automatic array allocation is only allowed via compile-time constants. So if you want to create an array with a user-entered size, you just have to use dynamic allocation -> pointers.
That said, I hope I was clear.

Where to delete the dynamic memory "char p"?

This is a hangman game program. I am declaring a char*p in the main which I can't understand why I am unable to delete later in the program when I don't need it. I tried it deleting later but it gives a heap memory error.
Also, I am a newbie in c++ - actually in programming - I will also appreciate if you can help me on how can I make the output of this program(on console) look more attractive and interactive. Like where should I use system("cls") commands more that can make it look more readable and remove non-essential information. Make a file in the same directory of the program with name either easy,medium or hard. so that it can have input from it when u run the program..
#pragma once
#include<iostream>
#include<string>
#include<ctime>
#include <cstdlib>
#include <stdlib.h>
#include <Windows.h>
#include<fstream>
#include<ctime>
#include <chrono> // for measuring time
using namespace std;
using namespace chrono;
//scoring the game with recard to time....
// filing : user name unique id and all that
//storing the name of user , his score, long story short, make a record of every user who passes by
int len = 0, letterCount = 0, size = 0, guesses = 6;
class tstamp
{
time_point<system_clock>tstart;
time_point<system_clock>tstop;
public:
void start()
{
tstart = system_clock::now();
}
void stop()
{
tstop = system_clock::now();
}
long long elasped()
{
return duration_cast<chrono::seconds>(tstop - tstart).count();
}
};
int checkWin(string a, char *p)
{
int count = 0;
int i = 0;
char *an = new char[a.length()];
string word = p;
for (i = 0; i < a.length(); i++)
{
if (a[i] == word[i])
count++;
}
if (count == i)
return 1; // 1 means the array is equal to the string == win
else
return 0; // not win
delete[]an; // using delete here for 1st
}
void resetData(string nameOfPlayer)
{
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::trunc);
//fout << "No Record";
fout.close();
}
void playerDetails(string nameOfPlayer, string a, bool status, float timeTaken)
{
char check = '\0';
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::app);
if (status == true)
fout << "Status : WON" << endl;
else
fout << "Status : LOST" << endl;
fout << "Word : " << a << endl;
fout << "Time taken to guess : " << timeTaken << " seconds" << endl;
fout << "********************************************";
fout << endl << endl;
fout.close();
}
string * grow(string *p, string temp) // to regrow the string array!!!!!
{
string* newArray = new string[size + 1];
for (int i = 0; i<size - 1; i++)
{
*(newArray + i) = *(p + i);
}
newArray[size - 1] = temp;
delete[] p;
return newArray;
}
char inGameMenu(char reset)
{
reset = '\0';
cout << "\n\t--->To reset your record press 'r' : ";
cout << "\n\n\t--->To display your previous record press 'd' : ";
cout << "\n\n\t--->To continue press 'x' : ";
cout << "\n\n\t--->To Exit the game press 'q' : ";
cout << endl << "\n\n\t--->Your Choice : ";
cin >> reset;
return reset;
}
string provideWord(string *contents, string a)
{
srand(time(NULL));
int i = rand() % size;
a = contents[i];
return a;
}
string* read(string fileName, string contents[])
{
string ext = ".txt";
fileName = fileName + ext;
fstream fin;
fin.open(fileName);
if (fin.is_open())
{
fin >> contents[0];
size++;
string temp;
while (fin >> temp)
{
size++;
contents = grow(contents, temp);
}
}
else
cout << "\n\tFile Not Found\n\n\n";
return contents;
}
char * makeAsterisks(string temp) // this will make astericks of the word player have to guess.
{
int len = temp.length();
char*p = new char[len];
for (int i = 0; i < len; i++)
{
p[i] = '-';
}
p[len] = '\0';
return p;
}
void displayRecord(string fileName, string display)
{
fstream fout;
fout.open(fileName + ".txt");
cout << "\n----------------------------------------------------------------------------------------------------------------";
if (fout.is_open())
{
cout << endl << endl;
while (getline(fout, display))
cout << display << endl;
}
else
cout << "\n!!No Record Found!!\nYou might be a new user\n";
cout << "\n----------------------------------------------------------------------------------------------------------------\n";
fout.close();
}
char * checkMyGuess(string word, char userGuess, char ar[])
{
bool flag = true;
for (int i = 0; i < word.length(); i++)
{
if (userGuess == word[i])
{
flag = false;
ar[i] = userGuess;
letterCount++;
}
}
if (flag == true)
{
_beep(450, 100);
cout << "\n\t!!!Wrong!!!\n";
len--;
guesses--;
}
return ar;
}
void rules()
{
system("Color 09 "); // for color effects
cout << "\n\n\t\t\t=====================\n";
cout << "\t\t\t||\tHANGMAN\t ||\n\t\t\t||\tRules\t ||"
<< "\n " << "\t\t\t=====================\n\n\n";
_beep(4000, 500);
system("Color 08 "); // for color effects
system("Color 07 "); // for color effects
cout << "\t--> Computer will think of a word and you have try\n" // rules
<< "\t to guess what it is one letter at a\n"
<< "\t time. Computer will draw a number of dashes \n "
<< "\tequivalent to the number of letters in the word.\n "
<< "\t If you suggest a letter that occurs\n "
<< "\t in the word, the computer will fill in the blank(s)\n"
<< "\t with that letter in the right place(s).\n"
<< "\t The session will be timed. \n\n";
cout << endl;
cout << "\t--> Total number of wrong choices : 6\n\n"; //wrong turns
cout << "\t--> Objective : Guess the word / phrase before you run out of choices!\n\n"; // obj
}
int checkForName(string fileName)
{
fileName = fileName + ".txt";
char line = '\0';
fstream fin;
char fromFile[7] = "\t\tName";
fin.open(fileName);
int i = 0,
check = 0;
while (fin.get(line) && i < 7)
{
if (line == fromFile[i++])
check++;
}
if (check == i - 1)
return 1;
else
return 0;
fin.close();
}
void checkForRecord(string fileName)
{
fileName = fileName + ".txt";
char line = '\0';
fstream fin;
char fromFile[7] = "No";
fin.open(fileName);
int i = 0,
check = 0;
while (fin.get(line) && i < 3)
{
if (line == fromFile[i++])
check++;
}
if (check == i - 1)
{
fin.open(fileName, ios::trunc);
fin.close();
}
fin.close();
}
int menu(int mode) // this function asks the user to enter the difficulty level of the game!!! You can't even beat medium!
{
system("cls");
cout << "Please select the Level of Game :\n";
cout << "1. Easy" << endl;
cout << "2. Medium" << endl;
cout << "3. Hard" << endl << endl;
cout << "Your Choice : ";
cin >> mode;
while (!(mode <= 3 && mode >= 1))
{
cout << endl << endl;
cout << "Please Enter the number of given choices: ";
cin >> mode;
}
return mode;
}
int comMenu(string nameOfPlayer, char reset)
{
string readData;
reset = '\0';
while (1)
{
reset = inGameMenu(reset);
if (reset == 'r')
{
resetData(nameOfPlayer);
system("cls");
Sleep(1);
}
else if (reset == 'd')
{
system("cls");
Sleep(1); // just to add a little delay!
cout << "Your Record Shows :--->\n";
displayRecord(nameOfPlayer, readData);
}
else if (reset == 'x')
break;
else if (reset == 'q')
break;
else
{
cout << "\n\n!!!Invalid Choice!!!\n\n";
}
}
return reset;
}
int main()
{
string nameOfPlayer;
char anyKey = '\0';
string name;
cout << endl;
rules();
cout << "Enter the name of player: ";
cin >> nameOfPlayer;
while (1)
{
char reset = '\0';
reset = comMenu(nameOfPlayer, reset);
if (reset != 'q') // check to exit the game
{
int uniquevar = checkForName(nameOfPlayer);
if (uniquevar != 1)
{
ofstream fout;
fout.open(nameOfPlayer + ".txt", ios::app);
fout << "\t\tName of Player : " << nameOfPlayer << endl << endl << endl;
fout.close();
}
while (1)
{
system("Color E0");
bool status = true; //initially win
size = 0,
len = 0,
letterCount = 0,
guesses = 6;
string a = ""; // it holds the word
string *contents = new string[1];
string name = "";
char b;
int mode = 0;
tstamp ts;
bool notRepeat[26] = { 0 };
if (anyKey == 'X' || anyKey == 'x')
break;
else
{
mode = menu(mode);
if (mode == 1)
name = "easy";
else if (mode == 2)
name = "medium";
else if (mode == 3)
name = "hard";
contents = read(name, contents);
cout << endl;
}
a = provideWord(contents, a);
delete[]contents;
len = a.length();
char *p = makeAsterisks(a); // detele it later
cout << "Total number of words to guesses: " << len << endl << endl;
cout << "Total guesses you have: 6\n";
cout << "Word :\n\n\t" << p << endl << endl;
ts.start(); // it starts counting the time...
while (guesses != 0)
{
cout << "Enter char: ";
cin >> b;
if (b >= '1' && b <= '9')
{
cout << "\n\nThere is not number in the given word\n\n";
continue;
}
int temp = b - 97; // it assigns the value of alphabet to temp i.e a=0,b=0 so on...
if (notRepeat[temp] != false)
{
cout << "\n\nYou've already used this word\n\n";
cout << "Remaining Choices: " << guesses << endl << endl;
continue;
}
else
{
p = checkMyGuess(a, b, p);
int checkingTheWin = checkWin(a, p);
if (checkingTheWin == 0)
{
}
else
{
cout << "\n\n\t*************You Won****************\n\n";
status = true; //true = win
break;
}
notRepeat[temp] = true;
cout << endl << endl;
cout << "Remaining Choices: " << guesses << endl;
cout << endl << '\t' << p << endl;
}
}
ts.stop();
cout << "Time Taken: " << ts.elasped() << " seconds\n\n";
p = NULL;
if (guesses == 0)
{
status = false; //false = lose
checkForRecord(nameOfPlayer);
playerDetails(nameOfPlayer, a, status, time); // right here it will create a file with the name of user
cout << "\n\nGame Over!!!\n\n";
cout << "\t\tThe word was \n\t\t\" " << a << "\"\n\n";
}
else
{
checkForRecord(nameOfPlayer);
playerDetails(nameOfPlayer, a, status, time); // right here it will create a file with the name of user
}
break;
} //ending block of while(1) first
system("color 07"); // shashka!!
}
if (reset == 'q') // to exit the game if the user decides so right away!!
break;
}
cout << "Exiting the Game\n\n";
_beep(3000, 500); // ending sound!
return 0;
}
In makeAsterisks you don't allow for the null terminator. You need to allocate one more character
char * makeAsterisks(string temp)
{
int len = temp.length();
char*p = new char[len + 1]; // <-- change here
for (int i = 0; i < len; i++)
{
p[i] = '-';
}
p[len] = '\0';
return p;
}
Now having said that, you are already using string, why not make life easier for yourself and use it everywhere? Here's makeAsterisks rewritten to use string.
string makeAsterisks(string temp)
{
return string(temp.length(), '-');
}

C++ Two dimensional array multiplication table

I am using C++ and want to do a 2-dimensional array. 10 rows and 3 columns. First column is(1 through 10). For Second column, user enters his/her choice of a number from (1-10) resulting in a times table displaying the results as follows: In this example the user's choice is '4':
1x4=4
2x4=8
3x4=12
4x4=16
5x4=20
6x4=24
7x4=28
8x4=32
9x4=36
10x4=40
I can't get the user's input to calculate correctly when using the for loop.
Well you can try this to get that output
#include<iostream>
using namespace std;
int main()
{
int n; //To take input
int table[10][3]; // Table
cout << "Input a number: ";
cin >> n;
// Generating Output
for (int i = 0; i < 10; i++)
{
table[i][0] = i + 1;
table[i][1] = n;
table[i][2] = table[i][0] * table[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << table[i][0] << " * " << table[i][1] << " = " << table[i][2]<<endl;
}
return 0;
}
Output
SOLVED: Everything seems to be working now!! Here's the code:
#include <iostream>
#include<cstdlib>
#include<iomanip>
#include <ctime>
using namespace std;
void displayTable(int table[10][3]);
bool testMe(int testTable[10][3]);
void createTables(int testTable[10][3], int ansTable[10][3], int
usersChoice);
bool AllAnswersAreTested(bool tested[10]);
void gradeMe(int testTable[10][3], int ansTable[10][3]);
void displayMenu();
int main()
{
srand(time(NULL));
int userInput = 0;
int tableChoice = 0;
int myTable[10][3] = {0};
int testTable[10][3];
int ansTable[10][3];
bool tested = false;
do
{
displayMenu(); //Display the menu of choices
cin >> userInput;
cout << endl;
switch (userInput) //Validate menu choices 1-4
{
case 1: //Display a users choice of table
displayTable(myTable);
break;
case 2: //Test user on users choice of table
cout << "What times table test would you like to take? > ";
cin >> tableChoice;
createTables(testTable, ansTable, tableChoice);
tested = testMe(testTable);
if (tested)
{
gradeMe(testTable, ansTable);
}
break;
case 3: //Display a new table of the users choice
displayTable(myTable);
break;
case 4: //Quit program menu option
cout << "Program ending.\n";
return 0;
default: //Invalid entry
cout << "You entered an invalid item number. Please enter a number from 1 to 4.\n";
cout << endl;
}
} while (userInput != 4);
return 0;
}
void displayTable(int myTable[10][3])
{
int num; //initialize local variables
//Ask the user what times table they would like to review
cout << "What times table would you like to review?" << endl;;
cout << "Please enter a value from 1 to 12 > \n";
cout << "\n";
cin >> num;
cout << endl;
for (int i = 0; i < 10; i++)
{
myTable[i][0] = i + 1;
myTable[i][1] = num;
myTable[i][2] = myTable[i][0] * myTable[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << setw(3)<< myTable[i][0] << " * " << myTable[i][1] << " = " << myTable[i][2] << endl;
}
cout << endl;
}
void createTables(int testTable[10][3], int ansTable[10][3], int usersChoice)
{
for (int i = 0; i < 10; i++)
{
testTable[i][0] = i + 1;
testTable[i][1] = usersChoice;
testTable[i][2] = 0;
ansTable[i][0] = i + 1;
ansTable[i][1] = usersChoice;
ansTable[i][2] = usersChoice * (i + 1);
}
}
bool testMe(int testTable[10][3])
{
bool tested[10] = { false, false, false, false, false,false, false, false, false, false };
while (!AllAnswersAreTested(tested))
{
int index = rand() % 10;
if (tested[index] == false)
{
int randomNum = testTable[index][0];
int tableChoice = testTable[index][1];
int answer;
cout << "What is " << randomNum << " X " << tableChoice << " = ";
cin >> answer;
testTable[index][2] = answer;
tested[index] = true;
}
}
return true;
}
bool AllAnswersAreTested(bool tested[10])
{
for (int i = 0; i < 10; i++)
{
if (tested[i] == false)
{
return false;
}
}
return true;
}
void gradeMe(int testTable[10][3], int ansTable[10][3])
{
int correctAnswers = 0;
for (int i = 0; i<10; i++)
{
if (testTable[i][2] == ansTable[i][2])
{
correctAnswers++;
}
}
int score = (correctAnswers * 10);
if (score == 100)
{
cout << "You passed the test! PERFECT SCORE!!" << endl;
cout << endl;
}
else if (score >= 70)
{
cout << "You passed the test. Your Score is: ";
cout << score;
cout << endl;
}
else if (score < 70)
{
cout << "You did not pass the test. Your Score is: ";
cout << score;
cout << endl;
}
}
//Display the menu function
void displayMenu()
{
cout << " Multiplication Tables" << endl;
cout << endl;
cout << " 1. Review MyTable" << endl;
cout << " 2. Test Me" << endl;
cout << " 3. Enter a New Multiplication Table (1-12)";
cout << " 4. Quit" << endl;
cout << " Enter a Menu Item > ";
}
#include <iostream>
using namespace std;
int main()
{
int a[100][100];
for(int i=1;i<10;i++){
for(int j=1;j<10;j++){
a[i][j] = (i)*(j);
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
There is how the output looks like:

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();

Move the rest of member of an Struct Array after sorting one of its members

I know there are way better and easier ways to do this, but for my class this is the only thing I can use and just work with what I have.
I am working on a Inventory Menu project, and I have to sort the "sku" number with a bubble sort, now my issue is that, I don't know how to move the other members at the same time.
Each sku number has its product's name, price and quantity. The code that I have sorts only the sku numbers and it works, the only thing is that the rest of the members stay in the same place.
What can I do?
NOTE: THE FUNCTION IS sortArray
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
using namespace std;
struct inventory {
string name;
int sku;
int quantity;
double price;
};
int size = 0;
void fillArray ( inventory[], int&, ifstream& );
void sortArray ( inventory[], int );
void displayIn ( inventory[], int );
int lookupSku ( inventory[], int, int );
int lookupName ( inventory[], int, string );
int main(){
// Constants for menu choices
const int DISPLAY_INVENTORY = 1,
LOOKUP_SKU = 2,
LOOKUP_NAME = 3,
QUIT_CHOICE = 4;
// Variables
int choice;
inventory products [100];
ifstream fin;
fin.open ("inventory.dat");
if (!fin)
{
cout << endl << endl
<< " ***Program Terminated. *** " << endl << endl
<< " Input file failed to open. " << endl;
system ( "PAUSE>NUL" );
return 1;
}
fillArray ( products, size, fin );
sortArray ( products, size );
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(2);
do
{
// Display the menu.
cout << "\n\t\t Manage Inventory Menu\n\n"
<< "1. Display inventory sorted by sku\n"
<< "2. Lookup a product by sku\n"
<< "3. Lookup a product by name\n"
<< "4. Quit the Program\n\n"
<< "Enter your choice: ";
cin >> choice;
cout << endl;
// Validate the menu selection.
while (choice < DISPLAY_INVENTORY || choice > QUIT_CHOICE)
{
cout << "Please enter a valid menu choice: ";
cin >> choice;
}
// Validate and process the user's choice.
if (choice != QUIT_CHOICE)
{
int indexSku,
indexName,
skuChoice;
string nameChoice;
switch (choice)
{
case DISPLAY_INVENTORY:
displayIn ( products, size );
break;
case LOOKUP_SKU:
cout << "Enter the Sku number: ";
cin >> skuChoice;
indexSku = lookupSku( products, size, skuChoice );
cout << "Product Name: " << products[indexSku].name << endl
<< "Sku: " << products[indexSku].sku << endl
<< "Quantity: " << products[indexSku].quantity << endl
<< "Price: " << products[indexSku].price << endl;
break;
case LOOKUP_NAME:
cout << "Enter name of product with no spaces: ";
cin >> nameChoice;
cout << endl;
indexName = lookupName ( products, size, nameChoice );
cout << "Product Name: " << products[indexName].name << endl
<< "Sku: " << products[indexName].sku << endl
<< "Quantity: " << products[indexName].quantity << endl
<< "Price: " << products[indexName].price << endl;
break;
}
}
} while (choice != QUIT_CHOICE);
fin.close ();
return 0;
}
void fillArray ( inventory product[], int &size, ifstream &fin )
{
int counter = 0;
while (fin >> product[counter].name)
{
fin >> product[counter].sku>> product[counter].quantity
>> product[counter].price;
counter ++;
}
size = counter;
}
void sortArray ( inventory product[], int size )
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if ( product[count].sku > product[count + 1].sku )
{
temp = product[count].sku;
product[count].sku = product[count + 1].sku;
product[count + 1].sku = temp;
swap = true;
}
}
} while (swap);
}
void displayIn ( inventory product[], int size )
{
for ( int i = 0; i < size; i++ )
{
cout << product[i].sku << " " << product[i].quantity << " "
<< product[i].price << " " << setw(4) << product[i].name
<<endl;
}
}
int lookupSku(inventory product[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (product[middle].sku == value)
{
found = true;
position = middle;
}
else if (product[middle].sku > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
int lookupName ( inventory product[], int size , string value )
{
int first = 0,
last = size - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (product[middle].name == value)
{
found = true;
position = middle;
}
else if (product[middle].name > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
You need to swap the entire struct, not just the member sku.
if ( product[count].sku > product[count + 1].sku )
{
inventory temp = product[count];
product[count] = product[count + 1];
product[count + 1] = temp;
swap = true;
}
The easiest way is to keep an array of pointers of inventory structs. Sort the elements on the same condition product[count]->sku > product[count + 1]->sku
but instead of swapping the sku values, swap the product[count] and product[count+1]. I hope it helps.
You can see here how to initalize an array of pointers to struct
source: http://www.cplusplus.com/forum/beginner/13778/