Binary Search Output Issue in Inventory Program c++ - c++

I am having issues with binary search function within my homework (I am completely done with it except for this one issue).
The program allows a user to manage the inventory of a small store that sells various products of any type. It will first read the inventory from a text file named “inventory.dat”, reading the product name, sku, quantity, and price. It will contain up to 100 products.
Then, it should offer the user a menu with the following options:
Display the inventory sorted by sku. (displayInventory function)
Lookup a product by sku. (lookupSku function)
Lookup a product by name. (lookupname function)
Quit
The program should perform the selected operation and then re-display the menu.
When I select option 2 and enter a sku number, my program outputs a random item's information instead of the one that was typed in by the user.
Here is my code starting in the main function along with the lookupBySku function:
int main()
{
// Initialize variables & array
int userInput;
//max array size
const int MAX_SIZE = 100; //const to make it constantly be 100
//declare and open input file
ifstream fin;
fin.open("inventory.dat");
//declare strings to hold data
string productName, sku, quantity, price;
if (!fin) // checking if file was inputted correctly or not.
{
cout << "File not found! Try again. " << endl;
return 1;
}
Inventory items[MAX_SIZE];
Inventory temp[MAX_SIZE];
cout << left << setw(20) << "Product Name " <<
left << setw(10) << "sku #" <<
left << setw(3) << "Quantity " <<
left << setw(0) << " Price\n";
//declare number of objects in inventory
int numOfObjects = 0;
while(!fin.eof())
{
getline(fin, productName);
getline(fin, sku);
getline(fin, quantity);
getline(fin, price);
if(productName == "")
{
break;
}
items[numOfObjects].name = productName;
cout << left << setw(20) << items[numOfObjects].name;
items[numOfObjects].sku = sku;
cout << left << setw(10) << items[numOfObjects].sku;
items[numOfObjects].quantity = quantity;
cout << left << setw(4) << items[numOfObjects].quantity;
items[numOfObjects].price = price;
cout << left << setw(0) <<"\t\t" << items[numOfObjects].price << endl;
++numOfObjects;
}
//check to see if there are more than 100 items
if(numOfObjects > 100)
{
cout << "File is too large, terminating program...\n";
return -1;
}
// Constants for menu choices
const int DISPLAY_BY_SKU = 1,
LOOKUP_BY_SKU = 2,
LOOKUP_BY_NAME = 3,
QUIT_CHOICE = 4;
do
{
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(2);
cout << "Manage Inventory Menu\n" <<endl;
cout << "1. Display inventory sorted by sku. " <<
"\n2. Lookup a product by sku. " <<
"\n3. Lookup a product by name. " <<
"\n4. Quit the program\n" << endl;
cout << "Enter your choice : ";
cin >> userInput;
cout << endl;
while (userInput < DISPLAY_BY_SKU || userInput > QUIT_CHOICE)
{
cout << "Please enter a valid menu choice: ";
cin >> userInput;
}
switch(userInput)
{
case DISPLAY_BY_SKU:
{
displayInventory(items, numOfObjects);
break;
}
case LOOKUP_BY_SKU:
{
lookupSku(items, numOfObjects);
break;
}
case LOOKUP_BY_NAME:
{
lookupName(items, numOfObjects);
break;
}
case 4:
cout << "Exiting the program." <<endl;
break;
}
}
while (userInput != QUIT_CHOICE);
fin.close();
return 0; }
void lookupSku (Inventory items[], int numOfObjects) {
string number;
int first = 0;
int last = numOfObjects - 1;
int middle;
int position = -1;
bool found = false;
cout << "Enter the sku that you'd like to search for : ";
cin >> number;
cout << endl;
while(!found && first <= last)
{
middle = (first + last)/2;
if(items[middle].sku == number)
{
found = true;
position = middle;
}
else if(items[middle].sku > number)
{
last = middle - 1;
}
else if(items[middle].sku < number)
{
first = middle + 1;
}
}
cout << "Your item is shown below : \n" << endl
<< "Product Name : "<< items[middle].name << endl
<< " Sku : " << items[middle].sku << endl
<<" Quantity : " << items[middle].quantity << endl
<< " Price : " << items[middle].price << endl
<< endl;
}

Related

i am trying to display employees based on their designation like hr,developer like that i tried a code but it is not displaying output

iam trying to display employees based on their designation like hr,developer like that i tried a code but it is not displaying output
void searchDeptReport()
{
system("cls");
char department[20];
int i;
;
bool found = false;
cout << "\nYou can Search only through the designation of Employees\n\n";
cout << "\nEnter the Department to get report : ";
cin >> department;
for (int i = 0; i <= num - 1; i++)
{
if (emp[i].designation == department)
{
cout << "\nName\t Emp ID\tGender\t Designation " << endl;
cout << "------------------------------------------------\n";
gotoXY(0, 7);
cout << "Name : " << emp[i].name << endl;
gotoXY(11, 7);
cout << "Employee Id : " << emp[i].code << endl;
gotoXY(21, 7);
cout << "Gender : " << emp[i].gender << endl;
gotoXY(35, 7);
cout << "Designation : " << emp[i].designation << endl;
found = true;
cout << "\n\nPress Any key for Menu..";
}
}
if (!found)
{
cout << "\n\nNo records Found...!!!\a";
cout << "\n\nPress Any key for Menu..";
}
getch();
}
enter image description here

C++ MDC Final - Sort Names in Records Alphabetically While in Array Struct of Type Char

I was able to write a program to pass my c++ class in college except for one feature. I was unable to create a function that sorted the names inside an array of structs with name of type char alphabetically. Please advise on how to tackle this problem.
I would need a function that sorts the accountRecords array alphabetically.
#include <iostream>
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
using namespace std;
//Structure Initilizations
const int NAME_SIZE = 25, ADDR_SIZE = 100, CITY_SIZE = 51, STATE_SIZE = 4, DATE_SIZE = 16, CUSTOMER_ID = 10, TRANSACTION_TYPE = 16;
struct MasterRecord
{
int customerID;
char name[NAME_SIZE]; // SORT THIS FIELD ALPHABETICALLY
char address[ADDR_SIZE];
char city[ADDR_SIZE];
char state[STATE_SIZE];
char zip[STATE_SIZE];
float accountBalance;
char lastTransactionDate[15];
};
struct TransactionRecord
{
int customerID;
char transactionType;
float amount;
char transactionDate[15];
};
//File Array Initializations
vector<MasterRecord> masterRecordList(101);
vector<TransactionRecord> transRecordList(101);
//Array List Record Position
int masterRecordArrayPosition = 0;
int transactionRecordArrayPosition = 0;
//User Menu Answer Variable Initialization
int userAnswer = 0;
string recordNotFoundAnswer = "";
//Print Function Prototypes
void showMenu();
void showMasterRecord(int);
void showTransactionRecord(int);
//Main Menu Function Prototypes
void newCustomerRecord(int);
void editCustomerRecord(int);
void deleteCustomerRecord(int);
int randomComputerID();
int searchMasterRecord(int);
void saveAccountRecords();
void saveTransRecords();
void newTransactionRecord(int);
//Placeholders Variables
int customerIDsearch = 0;
int customerIDSearchArrayPosition = 0;
int userNameCharactererror = 0;
//Function Loop Counters
int accountWriteCounter = 0;
int transWriteCounter = 0;
int showRecordCounter = 0;
int showTransCounter = 0;
//System time Declaration and Conversion for [lastTransactionDate]
time_t now = time(0);
tm *ltm = localtime(&now);
string currentYearInString = to_string(1900 + ltm->tm_year);
string currentMonthInString = to_string(1 + ltm->tm_mon);
string currentDayInString = to_string(ltm->tm_mday);
string currentDateInString = currentMonthInString + "/" + currentDayInString + "/" + currentYearInString;
char dateInChar[15];
//Main Program
int main()
{
//Final conversion of time in string to char for storage
strncpy_s(dateInChar, currentDateInString.c_str(), 15);
//Open MasterRecord file and read records to arrays
fstream masterRecord("masterRecord.dat", ios::in | ios::binary);
int listCounter = 0;
if (!masterRecord) {
cout << "Unable to open the user records file, creating file database....Done!" << endl;
masterRecord.open("masterRecord.dat", ios::out | ios::binary);
}
else {
while (!masterRecord.eof()) {
masterRecord.read(reinterpret_cast<char *>(&masterRecordList[listCounter]), sizeof(masterRecordList[0]));
if (masterRecordList[listCounter].customerID != 0) {
listCounter++;
}
masterRecordArrayPosition = listCounter;
}
masterRecord.close();
}
//Open Transaction Record and read to arrays
fstream transactionRecord("transactionRecord.dat", ios::in | ios::binary);
int listCounter2 = 0;
if (!transactionRecord) {
cout << "Unable to open the transaction file, creating file database....Done!" << endl << endl;
transactionRecord.open("transactionRecord.dat", ios::out | ios::binary);
}
else {
while (!transactionRecord.eof()) {
transactionRecord.read(reinterpret_cast<char *>(&transRecordList[listCounter2]), sizeof(transRecordList[0]));
if (transRecordList[listCounter2].customerID != 0) {
listCounter2++;
}
transactionRecordArrayPosition = listCounter2;
}
transactionRecord.close();
}
//Time Declaration Used to Generate Random IDs
srand((unsigned)time(0));
//Main user Program Loop
while (userAnswer != 6) {
showMenu();
cin >> userAnswer; cout << endl;
//Menu Input Data Validation
if (cin.fail()) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
cin.clear();
cin.ignore();
}
else {
if (userAnswer < 1 || userAnswer > 7) {
cout << "Please only enter numbers 1-6 for the corresponding menu selection." << endl;
userAnswer = 0;
}
}
//Menu Selection Switch Case
switch (userAnswer) {
case 1:
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
break;
case 2:
newTransactionRecord(transactionRecordArrayPosition);
break;
case 3:
cout << "Please enter the Customer ID you would like to Delete" << endl << endl; //[Delete Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
deleteCustomerRecord(customerIDSearchArrayPosition);
}
break;
case 4:
cout << "Please enter the Customer ID you would like to edit." << endl << endl; //[Search/Edit Customer Record] Function goes here
cin >> customerIDsearch;
customerIDSearchArrayPosition = searchMasterRecord(customerIDsearch);
if (customerIDSearchArrayPosition != 9999) {
editCustomerRecord(customerIDSearchArrayPosition);
}
else {
cout << "Record was not found, would you like to add a new record? Y = Yes, N = No" << endl << endl;
cin >> recordNotFoundAnswer;
if (recordNotFoundAnswer == "Y" | recordNotFoundAnswer == "y") {
newCustomerRecord(masterRecordArrayPosition);
cout << "Record has been saved." << endl << endl;
}
else if (recordNotFoundAnswer == "N" | recordNotFoundAnswer == "n") {
userAnswer = 0;
}
}
break;
case 5:
cout << setw(212) << "Please find all customer records in the database" << endl << endl; //[Show all Records] Function goes here
cout << setw(40) << "Name:" << setw(10) << "ID:" << setw(23) << "Street Address:" <<setw(10) << "ZIP:" << setw(16) << "L.Trans Date:" << setw(11) << "Balance: " << endl;
while (showRecordCounter < 100) {
if (masterRecordList[showRecordCounter].customerID != 0) {
showMasterRecord(showRecordCounter);
}
showRecordCounter = showRecordCounter + 1;
} showRecordCounter = 0;
userAnswer = 0;
cout << endl;
break;
case 6:
cout << "Saving changes to database...Done!" << endl;
saveAccountRecords();
saveTransRecords();
cout << "Done!" << endl;
break;
case 7:
cout << "Showing all transaction Records:" << endl << endl;
while (showTransCounter < 100) {
if (transRecordList[showTransCounter].customerID != 0) {
showTransactionRecord(showTransCounter);
}
showTransCounter = showTransCounter + 1;
} showTransCounter = 0;
userAnswer = 0;
break;
}
}
return 0;
}
//Databas Management Functions
void saveAccountRecords() {
fstream masterRecord("masterRecord.dat", ios::out | ios::binary);
while (accountWriteCounter < 100) {
masterRecord.write(reinterpret_cast<char *>(&masterRecordList[accountWriteCounter]), sizeof(masterRecordList[0]));
accountWriteCounter++;
}
masterRecord.close();
}
void saveTransRecords() {
fstream transRecord("transactionRecord.dat", ios::out | ios::binary);
while (transWriteCounter < 100) {
transRecord.write(reinterpret_cast<char *>(&transRecordList[transWriteCounter]), sizeof(transRecordList[0]));
transWriteCounter++;
}
transRecord.close();
}
//Random Function
int randomComputerID() {
int randomNumber;
randomNumber = (rand() % 1000) + 10000;
return randomNumber;
}
//Program Print Functions
void showMenu() {
cout << "Welcome to your C++ company terminal! Please enter one of the options below to continue." << endl << endl;
cout << "1. New Customer Record" << endl;
cout << "2. New Transaction Record" << endl;
cout << "3. Delete Customer Record" << endl;
cout << "4. Edit Customer Record" << endl;
cout << "5. Show all Account Records in Database" << endl;
cout << "6. Exit and Save Changes to Database" << endl << endl;
cout << "Please enter the number for the correspondent action you would like to perform:" << endl;
}
void showMasterRecord(int arrayNum) {
cout << setw(40)
<< masterRecordList[arrayNum].name << setw(10) << masterRecordList[arrayNum].customerID << setw(23)
<< masterRecordList[arrayNum].address << setw(10)
<< masterRecordList[arrayNum].zip << setw(16)
<< masterRecordList[arrayNum].lastTransactionDate << setw(6) <<"$"
<< masterRecordList[arrayNum].accountBalance; cout << endl;
}
void showTransactionRecord(int arrayNum) {
cout << "Customer ID: " << transRecordList[arrayNum].customerID << endl;
cout << "Amount: $" << transRecordList[arrayNum].amount << endl;
cout << "Transaction Type: " << transRecordList[arrayNum].transactionType << endl;
cout << "Transaction Date: " << transRecordList[arrayNum].transactionDate << endl << endl;
}
//Main Menu Functions [Please insert your functions here and prototype them above].
void newCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
masterRecordList[arrayNum].customerID = randomComputerID();
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
do
{
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 25);
if (cin.fail()) {
cout << endl << "Please enter only characters up 25 chracters for your name." << endl;
userNameCharactererror = 1;
cin.clear();
cin.ignore(80, '\n');
}
else {
userNameCharactererror = 0;
}
} while (userNameCharactererror == 1);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Opening Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
masterRecordArrayPosition = masterRecordArrayPosition + 1;
}
void editCustomerRecord(int arrayNum) {
cout << "Customer ID: ";
cout << masterRecordList[arrayNum].customerID; cout << endl;
cin.ignore();
cout << "Name: ";
cin.getline(masterRecordList[arrayNum].name, 51);
cout << "Address: ";
cin.getline(masterRecordList[arrayNum].address, 100);
cout << "City: ";
cin >> masterRecordList[arrayNum].city;
cout << "State: ";
cin >> masterRecordList[arrayNum].state;
cout << "Zip Code: ";
cin >> masterRecordList[arrayNum].zip;
cout << "Edit Balance: $";
cin >> masterRecordList[arrayNum].accountBalance; cout << endl; cout << endl;
}
void deleteCustomerRecord(int arrayNum) {
if (masterRecordList[arrayNum].accountBalance == 0)
{
masterRecordList[arrayNum].customerID = 0;
cout << "Record has been deleted" << endl << endl;
}
else {
cout << "Unable to delete record, customer accounts holds a positive balance" << endl << endl;
}
}
int searchMasterRecord(int customerID) //Search by customer name and returns array position
{
int arrayPosition = 0;
int arrayCounter = 0;
int customerIdPlaceholder = 0;
while (arrayCounter < 100) {
customerIdPlaceholder = masterRecordList[arrayCounter].customerID;
if (customerIdPlaceholder == customerID) {
cout << "Record has been found!" << endl << endl;
arrayPosition = arrayCounter;
arrayCounter = 100;
}
else {
arrayPosition = 9999;
}
arrayCounter = arrayCounter + 1;
}
return arrayPosition;
};
void newTransactionRecord(int arrayNum) {
// Request customer ID and transaction type from the user
cout << "Customer ID: ";
cin >> transRecordList[arrayNum].customerID;
cin.ignore();
cout << "Date: ";
strncpy_s(transRecordList[arrayNum].transactionDate, dateInChar, 15);
cout << transRecordList[arrayNum].transactionDate << endl;
cout << "Transaction Type [D = Deposit] [W = Withdrawal]: ";
cin >> transRecordList[arrayNum].transactionType;
cout << "Amount: $";
cin >> transRecordList[arrayNum].amount;
//Search for customer account, update balance, and assign last transaction date
customerIDSearchArrayPosition = searchMasterRecord(transRecordList[arrayNum].customerID);
if (customerIDSearchArrayPosition != 9999) {
if (transRecordList[arrayNum].transactionType == 'D') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance + transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Deposit Successful! " << endl << endl;
}
else if (transRecordList[arrayNum].transactionType == 'W') {
masterRecordList[customerIDSearchArrayPosition].accountBalance = masterRecordList[customerIDSearchArrayPosition].accountBalance - transRecordList[arrayNum].amount;
strncpy_s(masterRecordList[customerIDSearchArrayPosition].lastTransactionDate, dateInChar, 9);
cout << "Withdrawl Successful" << endl << endl;
}
}
else {
cout << "Customer account record was not found, transaction was not saved." << endl << endl;
}
transactionRecordArrayPosition = transactionRecordArrayPosition + 1;
}
Something along these lines:
std::sort(masterRecordList.begin(),
masterRecordList.begin() + masterRecordArrayPosition,
[](const MasterRecord& l, const MasterRecord& r) {
return strcmp(l.name, r.name) < 0;
});

Error when creating an address database in c++

Hello everyone I have been working on my lab for a few days now and I think I am close to completion. However when I go to build my program I keep getting the errors unresolved external symbol main reference in function int cdecl. Its also giving me the error of 1 unresolved externals. I am not sure what this means since I am new to writing in C++ and any help would be greatly appreciated.
Here is what I have so far
enter code here
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
string * split(string, char);
const char FileName[] = "TestAddress.txt"; //File name from where to read the characters
int _tmain()
{
menu();
return 0;
}
void menu(void) { //Display main menu and call relevant functions
char input;
while (1)
{
cout << endl;
cout << "|---------------------MENU----------------------------|" << endl; //Menu display with style
cout << "| (A)ppend Records, (S)how Records, (E)xit |" << endl; //3 options that can be selected
cout << "|-----------------------------------------------------|";
cout << endl << endl;
cin >> input;
if (input == 'A' || input == 'a')
writeData();//Append data to the file
else if (input == 'S' || input == 's')
readData(); //Read records from the file and display
else if (input == 'E' || input == 'e')
exit(0);// Exit application
else
cout << endl << "Invalid Input!!! Please try again." << endl << endl; //In case of invalid input, menu will be displayed again
}
}//end menu
void writeData(void) {//Append data to the file
string Name, Street, City, State, ZipCode, input;
fstream outputFile;
outputFile.open(FileName, fstream::app); //Open the file with append mode
do {
cout << endl << endl;
cout << "Please enter Name:" << endl;
cin >> Name; //Input Name
cout << endl;
cout << "Please enter Street:" << endl;
cin >> Street;//Input Street Address
cout << endl;
cout << "Please enter City:" << endl;
cin >> City; //Input City
cout << endl;
cout << "Please enter State:" << endl;
cin >> State;// Input State
cout << endl;
cout << "Please enter ZipCode:" << endl;
cin >> ZipCode; //Input Zipcode
cout << endl;
cout << endl;
outputFile << Name << "," << Street << "," << City << "," << State << "," << ZipCode << endl; //Write all data to the file
//Displaying the record which is input recently fromt he user
cout << endl; //Displaying heading with style
cout << "|-----------------------------------------------------|" << endl;
cout << "| Append Records |" << endl;
cout << "|-----------------------------------------------------|" << endl << endl;
cout << "Name.........." << Name << endl;
cout << "Street........" << Street << endl;
cout << "City.........." << City << endl;
cout << "State........." << State << endl;
cout << "Zip Code......" << ZipCode << endl;
cout << endl << endl;
do {
cout << "Enter Another Record?(Y/N)" << endl;
cin >> input;//In case if user wants to enter another rcord
} while (input != "Y"&& input != "y" && input != "N"&& input != "n"); //Until the user presses 'y' or 'n'
} while (input == "Y" || input == "y"); //If user wants to add another record continue or else display menu again
outputFile.close(); //Close file
}//end write data
void readData(void) {//Read records from the file and display
string Name, Street, City, State, ZipCode;
char* line = new char[2000]; //pointing to a vriable that will be having a record detail
ifstream inputFile;
int RecordNumber = 1;
inputFile.open(FileName, fstream::in);//Open the file with read mode
cout << endl;
cout << "|-----------------------------------------------------|" << endl; //Heading display with style
cout << "| Show Records |" << endl;
cout << "|-----------------------------------------------------|";
while (!inputFile.eof())
{
inputFile.getline(line, 2000); //Read one record from the file
string * fields = split(line, ',');//Split the records based on the prsence of ','
if (fields[0] == "") //In case of '\n' has encountered
continue; //Steop processing and continue the loop again
cout << "" << endl;
cout << "Record #" << RecordNumber << endl; //Displaying record with style
cout << "Name.........." << fields[0] << endl;
cout << "Street........" << fields[1] << endl;
cout << "City.........." << fields[2] << endl;
cout << "State........." << fields[3] << endl;
cout << "Zip Code......" << fields[4] << endl;
cout << endl << "-------------------------------------------------------" << endl << endl;
RecordNumber++; //Increment record number
}
}//end read data
string * split(string theLine, char theDeliminator) {
//determine how many splits there will be so we can size our array
int splitCount = 0;
for (int i = 0; i < theLine.size(); i++) { //Read the whole string (theLine) and count for all ',' encountered
if (theLine[i] == theDeliminator)
splitCount++;
}
splitCount++; //add one more to the count because there is not an ending comma
//create an array to hold the fields
string* theFieldArray;
theFieldArray = new string[splitCount];
//split the string into seperate fields
string theField = "";
int commaCount = 0;
for (int i = 0; i < theLine.size(); i++) { //read each character and look for the deliminator
if (theLine[i] != theDeliminator) {
theField += theLine[i]; //build the field
}
else { //the deliminator was hit so save to the field to the array
theFieldArray[commaCount] = theField; //save the field to the array
theField = "";
commaCount++;
}
}
theFieldArray[commaCount] = theField; //the last field is not marked with a comma...
return theFieldArray;
} //end split

C++ fstream building but not running

I'm building a program for my class the requires us to import data from a .txt file and the item names/ prices will be used to calculate saltes tax and grand total. My teacher put this up as an example, but I can't get it to run.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{ // Beginning of main function
string name;
ifstream data_in;
ofstream data_out;
int cnt=0;
int number;
struct Item
{
int item_n;
char disc[50];
float price;
};
Item store[999];
data_in.open("cost.txt");
data_out.open("file_out.txt");
while(!data_in.eof())
{
//cout << "Enter in the item number: ";
data_in >> store[cnt].item_n;
//cout << "Enter in the description for item number " << store[cnt].item_n << ": ";
data_in >> store[cnt].disc;
//cout << "Enter in the price for the " << store[cnt].disc << ": $";
data_in >> store[cnt].price;
cnt++;
}
cout << endl << endl;
number = cnt;
for (cnt=0; cnt<number; cnt++)
{
name = store[cnt].disc;
cout << setw(5) << store[cnt].item_n << " " << store[cnt].disc << setw(16-name.length()) << "$" << setw(9) << store[cnt].price << endl;
}
for (cnt=0; cnt<number; cnt++)
{
name = store[cnt].disc;
data_out << setw(5) << store[cnt].item_n << " " << store[cnt].disc << setw(16-name.length()) << "$" << setw(9) << store[cnt].price << endl;
}
return 0;
}
And this is the information in the cost.txt file
Books 45.01
Pens 21.03
Pencils 10.90
Hats 50.00
Caps 800.00
Food 1.00
The code you've written reads three things for each Item: the item number, the description, and price.
The sample data file you shown contains only two things for each item: what looks to be a description, and a price.
The expected data format does not match the contents of the input file. This code will never work, as is. One or the other is wrong. Plus all the other problems with the code, as mentioned in the comments.
Try the following changes, the rest of your code seems to work:
data_in.open("cost.txt");
data_out.open("file_out.txt");
if (!data_in.is_open() || !data_out.is_open()) //Test if files opened correctly...
{
cout << "Failed to open a file!\n";
return 1;
}
float SalesTotal = 0;
while(true)
{
if (!(data_in >> store[cnt].disc))
{
//Failed to read first element in this record - could be eof or format error
if (data_in.eof())
break; //eof - all records read.
cout << "Format error first field\n";
return 1; //format error on first field.
}
if (!(data_in >> store[cnt].price))
{
cout << "Format error second field\n";
return 2; //format error on second field.
}
store[cnt].item_n = cnt + 1; //Item number is not a field in your file, use the counter...
SalesTotal += store[cnt].price;
cnt++;
}
if (!cnt)
{
cout << "No records read\n";
return 3; //No valid records read.
}
float GrandTotal = ((SalesTotal / 100) * 6) + SalesTotal;
cout << "Sales total: " << SalesTotal << " Grand total:" << GrandTotal << "\n";

Creating Table headers?

OK, in this program I am required to make a table based of user input. The problem is I cannot figure out how to get the table headers to properly align with the information that is displayed. The table headers would not line up from lets say if the user enters in Michael for player one and Michael Jordan for player 2. Any advice to allow the headers to properly align with the displayed input regardless of character length would be greatly appreciated, thanks.
Here is my code:
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;
//struct of Basketball Player info
struct BasketballPlayerInfo
{
string name; //player name
int playerNum, //player number
pointsScored; //points scored
};
int main()
{
int index, //loop count
total = 0; //hold total points
const int numPlayers = 5; //nuymber of players
BasketballPlayerInfo players[numPlayers]; //Array of players
//ask user for Basketball Player Info
cout << "Enter the name, number, and points scored for each of the 5 players.\n";
for (index = 0; index < numPlayers; index++)
{
//collect player name
cout << " " << endl;
cout << "Enter the name of player # " << (index + 1);
cout << ": ";
//input validation
if(!(getline(cin, players[index].name)))
{
cout << "Player Name must be alphabetical characters only!\n";
cout << "Program terminating please start over." << endl;
system("pause");
exit(0);
}
//getline(cin, players[index].name);
//collect players number
cout << "Enter the number of player # " << (index + 1);
cout << ": ";
//input validation
if(!(cin >> players[index].playerNum))
{
cout << "Player Name must be numeric characters only!\n";
cout << "Program terminating please start over." << endl;
system("pause");
exit(0);
}
//collect points scored
cout << "Enter points scored for player # " << (index + 1);
cout << ": ";
//input validation
if(!(cin >> players[index].pointsScored))
{
cout << "Player Name must be numeric characters only!\n";
cout << "Program terminating please start over." << endl;
system("pause");
exit(0);
}
cin.ignore();
}
//display
cout << "\n";
cout << "Here is the information for each player: \n";
cout << fixed << showpoint << setprecision(2);
cout << "\n";
cout << " \tName\tNumber\tPoints\n";
cout << "------------------------------------------------" << endl;
for(index = 0; index < numPlayers; index++)
{
cout << "Player # " << (index + 1);
cout << ": \t" << players[index].name << "\t" << players[index].playerNum << "\t" << players[index].pointsScored << endl;
cout << "------------------------------------------------" << endl;
}
//display total points scored by all players
for(index = 0; index < numPlayers; index++)
{
//hold total
total += players[index].pointsScored;
}
cout << "Total Points scored are: " << total << endl;
system("pause");
return 0;
}
you could use setw io manipulator which comes under #include <iomanip>.
cout << setw(20) << "Column1"
<< setw(20) << "Column2"
<< setw(8) << "Column3";
or you could use Boost library
// using Boost.Format
cout << format("%-20s %-20s %-8s\n") % "Column1" % "Column2" % "Column3";
Take a look at the setw and setfill functions. You can use them to assign a minimum width to your columns, which will make for much cleaner output formatting than tabs.