In C++, I'm trying to input movie's names and years of releasing and store them in a database/structure. Before I ask for the titles and years to be inputted. I have the user log on with credentials. In this case, the username is "rusty" and the password is "rusty".
The issue I'm having is the after the credentials are verified, the first movie title to input into the database/structure is skipped. I believe this has something to do with me using the _getch function, but I'm not totally sure.
My code is below. My output looks like this:
Please enter your username
rusty
Please enter your password
Access granted! Welcome rusty
Enter title: Enter year: (input movie year)
Enter title: (input movie title)
Enter year: (input movie year)
Enter title: (input movie title)
....
#include <iostream>
#include <string>
#include <sstream>
#include <conio.h>
using namespace std;
//function prototype
int username_and_pass();
#define NUM_MOVIES 6
struct movies_list{
string title;
int year;
}films[NUM_MOVIES];
// prototype with function declaration
void sort_on_title(movies_list films[], int n)
{
movies_list temp;
for (int i = 0; i < n - 1; i++)
{
if (films[i].title>films[i + 1].title)
{
temp = films[i];
films[i] = films[i + 1];
films[i + 1] = temp;
}
}
}// end of sort_on_title function
void printmovie(movies_list movie)
{
cout << movie.title;
cout << " (" << movie.year << ") \n";
}
void search_on_title(movies_list films[], int n, string title)
{
bool flag = false;
for (n = 0; n < NUM_MOVIES; n++)
{
if (films[n].title == title)
{
cout << "Title: " << films[n].title << endl;
cout << "Year of Release: " << films[n].year << endl;
cout << "\n";
flag = true;
}
}
if (flag == false)
cout << "Search on title not found!" << endl;
}// end of search_on_title function
void search_on_year(movies_list films[], int n, int year)
{
bool flag = false; // check on existence of record
for (n = 0; n < NUM_MOVIES; n++)
{
if (films[n].year == year) // display if true
{
cout << "Title: " << films[n].title << endl;
cout << "Year of Release: " << films[n].year << endl;
cout << "\n";
flag = true;
}
}
if (flag = false)
cout << "Search on title not found!" << endl;
}// end of search_on_title function
int menu()
{
int choice;
cout << " " << endl;
cout << "Enter 1 to search on titles " << endl;
cout << "Enter 2 to search on years " << endl;
cin >> choice;
cout << "\n";
return choice;
}// end of menu function
int username_and_pass()
{
string uName;
string password;
int value;
char ch;
cout << "Please enter your username\n";//"rusty"
cin >> uName;
cout << "Please enter your password\n";//"rusty"
ch = _getch();
while (ch != 13)//As long as the user doesn't press Enter
{//(enter is ASCII code 13) continue reading keystrokes from the screen.
password.push_back(ch);
cout << '*';
ch = _getch();
}
if (uName == "rusty" && password == "rusty")
{
cout << "\n\nAccess granted! Welcome " << uName << "\n\n" << endl;
value = 1
}
else
{
cout << "Invalid credentials" << endl;
value = 0;
}
return value;
}// end of username_and_pass function
int main()
{
string mystr;
int n;
string response;
int value = 0;
do
{
value = username_and_pass();
} while (value==0);
if(value==1)
{
for (n = 0; n < NUM_MOVIES; n++)
{
cout << "Enter title: ";
getline(cin, films[n].title);
cout << "Enter year: ";
getline(cin, mystr);
stringstream(mystr) >> films[n].year;
}
//sorts records
sort_on_title(films, NUM_MOVIES);
cout << "\nYou have entered these movies:\n";
for (n = 0; n < NUM_MOVIES; n++)
printmovie(films[n]);
//menu
int choice = 0;
choice = menu();
if (choice == 1)
{
string searchTerm;
cout << "What is the movie you want to search for? " << endl;
cin >> searchTerm;
cout << " " << endl;
search_on_title(films, NUM_MOVIES, searchTerm);
}
else
{
int searchTermYear;
cout << "What is the year you want to search for? " << endl;
cin >> searchTermYear;
cout << " " << endl;
search_on_year(films, NUM_MOVIES, searchTermYear);
}
cout << "Would you like to query the database again? (Y/N)" << endl;
cin >> response;
if (response == "Y" || "y")
{
choice = menu();
if (choice == 1)
{
string searchTerm;
cout << "What is the movie you want to search for? " << endl;
cin >> searchTerm;
cout << " " << endl;
search_on_title(films, NUM_MOVIES, searchTerm);
}
else
{
int searchTermYear;
cout << "What is the year you want to search for? " << endl;
cin >> searchTermYear;
cout << " " << endl;
search_on_year(films, NUM_MOVIES, searchTermYear);
}
}
}
return 0;
}
Flush all the content's of input buffer.
Please go to following link to flush contents of input buffer.
https://stackoverflow.com/a/7898516/4112271
I am not sure what causing you this problem.But can you try using cin.clear(). Place it before you ask for input of title.
cin.clear();
cout << "Enter title: ";
getline(cin, films[n].title);
cout << "Enter year: ";
getline(cin, mystr);
stringstream(mystr) >> films[n].year;
Related
Sometimes when I run the program, it runs perfectly fine. Sometimes I get an infinite loop that just keeps displaying my first choice menu. I tried searching for the error and I couldn't figure it out. I thought there was an error in my input statement when I got the menuChoice, but I was unable to troubleshoot it out. Should I be checking the value of menuChoice more often? To better specify, I am referring to the second do-while loop, the one that reprints the menu choices after each iteration.
main.cpp
#include <vector>
#include <fstream>
#include <iostream>
#include "course.hpp"
using namespace std;
int main() {
int menuChoice, searchMenuChoice;
string fileName;
string line;
ifstream inStream;
string searchName;
string searchPrefix;
int searchNum;
vector<Course> courseList;
vector<int> enrolledClasses;
do{
cout << "Please enter the file that contains othe course data: ";
cin >> fileName;
inStream.open(fileName);
}while (!inStream.is_open());
cout << endl;
while (getline(inStream, line)){
courseList.push_back(Course(line));
}
cout << "Welcome to Banner NE, short for Never Existed!" << endl;
do {
cout << "\n"<< "---------------------------------------------" << endl;
cout << "1 - List all available classes" << endl;
cout << "2 - Search for a course" << endl;
cout << "3 - View your current enrolled courses" << endl;
cout << "4 - Enroll in course" << endl;
cout << "5 - Exit" << endl;
cout << "Make your selection here: ";
cin >> menuChoice;
cout << endl;
if (menuChoice == 5){
cout << "Thank you for using Banner NE and have a nice day!" << endl;
return 0;
}
if (menuChoice == 2) {
cout << endl;
cout << "Would you like to search by" << endl;
cout << "1 - Course number" << endl;
cout << "2 - Available seats remaining" << endl;
cout << "3 - Instructor name" << endl;
cout << "4 - Course prefix" << endl;
cout << "Make your selection: ";
cin >> searchMenuChoice;
if (searchMenuChoice == 2) {
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).getSeatsRemaining() > 0)
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 1) {
cout << "Please enter the course number: ";
cin >> searchNum;
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).MatchesCourseNumberSearch(searchNum))
courseList.at(i).printCourse();
break;
}
}
if (searchMenuChoice == 3) {
cout << "Please enter the name of the instructor: ";
cin >> searchName;
for (int i = 0; i < courseList.size(); i++) {
if (courseList.at(i).MatchesInstructorSearch(searchName))
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 4){
cout << "Please enter the prefix you would like to search for: ";
cin >> searchPrefix;
for (int x = 0; x < courseList.size(); x++)
if (courseList.at(x).MatchesPrefix(searchPrefix))
courseList.at(x).printCourse();
}
}
if (menuChoice == 1) {
for (int x = 0; x < courseList.size(); x++){
cout << "ID: " << x << "\t";
courseList.at(x).printCourse();
cout << endl;
}
}
if (menuChoice == 4) {
int classEnrollment;
cout << "Please enter the ID number of the class you would like to enroll: ";
cin >> classEnrollment;
if (courseList.at(classEnrollment).Enroll()){
enrolledClasses.push_back(classEnrollment);
cout << "You have enrolled in ID " << classEnrollment << endl;
}
else
cout << "There was not enough space, sorry." << endl;
}
if (menuChoice == 3){
for (int i = 0; i < enrolledClasses.size(); i++){
courseList.at(enrolledClasses.at(i)).printCourse();
cout << endl;
}
if (enrolledClasses.size() == 0 )
cout << "You are not currently enrolled in any classes." << endl;
}
} while (menuChoice != 5);
return 0;
}
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;
});
Right now my problem seems to be focused on the saveFile function.
I will post the entire program here, so dont be ired when see a whole bunch of code... just look at the saveFile function at the bottom... I am posting all the code JUST IN CASE it will help you help me solve my problem.
Now for defining the apparent problem to you all: I can edit the file throughout the life of the console app with the updateSale function as I run it, but when I use the saveFile function and put in 'y' to save, the differences that are visible after using the updateSales function DO NOT get saved to the actual sales file called "salespeople.txt" and I do not understand why.
this is what the salespeople.txt looks like:
Schrute 25000
Halpert 20000
Vance 19000
Hudson 17995.5
Bernard 14501.5
now here is the program:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
//variables--------------------------------------------------------
int lineCount = 0;
//prototypes-------------------------------------------------------
int getIndexLargest(string[], double[]);
void displaySalesPeople(string[], double[]);
bool readSalesFile(string[], double[]);
void updateSales(string[], double[]);
int saveFile(string, string[], double[], int);
int main()
{
string fileName;
int arrayLength;
ifstream readSales;
string salesPersonName[5];
double saleAmount[5];
bool flag = false;
int options;
do
{
cout << "1) Open sales person file. "<< endl;
cout << "2) Display sales person information. "<< endl;
cout << "3) Update sales. " << endl;
cout << "4) Get best sales person. " << endl;
cout << "5) Exit. " << endl;
cout << "Please enter a number 1-5 to select an option." <<endl;
cin >> options;
if(options == 1)
{
flag = readSalesFile(salesPersonName, saleAmount);
}
else if(options == 2)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
displaySalesPeople(salesPersonName, saleAmount);
}
else if(options == 3)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
else
updateSales(salesPersonName, saleAmount);
}
else if(options == 4)
{
if(flag == false)
{
cout << "Please open sales file before selecting this option. Try again" << endl;
}
getIndexLargest(salesPersonName, saleAmount);
}
else if(options == 5)
{
char choice;
cout << "Enter character y to save... anything else will exit without saving: " << endl;
cin >> choice;
if(choice == 'y')
{
saveFile(fileName, salesPersonName, saleAmount, arrayLength);
cout << "File saved. " << endl;
}
else
{
cout << "closing program" << endl;
}
}
}
while(options != 5);
return 0;
}
//functions---------------------------------
bool readSalesFile(string salesPersonName[], double saleAmount[])
{
bool flag = false;
ifstream readSales;
string fileName;
cout << "Please enter the path to your sales people file: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
while(readSales.fail())
{
cout << "Failed. Please enter the path to your sales file again: ";
getline(cin, fileName);
readSales.open(fileName.c_str());
}
if(readSales.good())
{
flag = true;
cout << lineCount;
string name = " ";
double amount =0.00;
int i = 0;
while(!readSales.eof())
{
readSales >> name;
readSales >> amount;
salesPersonName[i] = name;
saleAmount[i] = amount;
i++;
}
for(i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
readSales.close();
}
readSales.close();
return flag;
}
void displaySalesPeople(string salesPersonName[], double saleAmount[])
{
for(int i = 0; i < 5; i++)
{
cout << "Sales person name: " << salesPersonName[i] << endl;
cout << "Sale amount: $" << saleAmount[i] << endl;
}
}
void updateSales(string salesPersonName[], double saleAmount[])
{
bool flag = false;
string findName;
double moneyAmount;
cout << "Enter name of sales person you want to modify: " << endl;
cin >> findName;
for(int i = 0; i < 5; i++)
{
if(findName == salesPersonName[i])
{
cout << "Enter the sale amount you would like to modify: " << endl;
cin >> moneyAmount;
saleAmount[i] += moneyAmount;
cout << saleAmount[i] << endl;
flag = true;
}
}
if(flag == false)
{
cout << " name not found" << endl;
}
}
int getIndexLargest(string salesPersonName[], double saleAmount[])
{
ifstream readSales;
while(!readSales.eof())
{
double largestSale = 0.00;
string largestSalesPerson;
int i = 0;
lineCount++;
readSales >> salesPersonName[i];
readSales >> saleAmount[i];
if(saleAmount[i] > largestSale)
{
largestSale = saleAmount[i];
largestSalesPerson = salesPersonName[i];
}
cout << "Best sales person : "<< largestSalesPerson << " $" <<setprecision(2)<<fixed<< largestSale << endl;
}
}
int saveFile(string fileName, string salesPersonName[], double saleAmount[], int arrayLength)
{
ofstream saveFile(fileName.c_str());
saveFile.open(fileName.c_str());
for(int i = 0; i < 5; i++)
{
saveFile << salesPersonName[i] << " " << saleAmount[i] << endl;
}
saveFile.close();
return 0;
}
You are trying t open your file twice:
ofstream saveFile(fileName.c_str()); // this opens the file
saveFile.open(fileName.c_str()); // so does this
That will put the file in an error state so no writing will happen.
Just do this:
ofstream saveFile(fileName.c_str()); // this opens the file
And that should work.
Or else you can do this:
ofstream saveFile; // this does not open the file
saveFile.open(fileName.c_str()); // but this does
And that should work too.
Sorry for the lack of previous explanation to my school's assignment. Here's what I'm working with and what I have / think I have to do.
I have the basic structure for populating the address book inside an array, however, the logic behind populating a text file is a bit beyond my knowledge. I've researched a few examples, however, the implementation is a bit tricky due to my novice programming ability.
I've gone through some code that looks relevant in regard to my requirements:
ifstream input("addressbook.txt");
ofstream out("addressbook.txt");
For ifstream, I believe implementing this into the voidAddBook::AddEntry() would work, though I've tried it and the code failed to compile, for multiple reasons.
For ostream, I'm lost and unsure as to how I can implement this correctly. I understand basic file input and output into a text file, however, this method is a bit more advanced and hence why I'm resorting to stackoverflow's guidance.
#include <iostream>
#include <string.h> //Required to use string compare
using namespace std;
class AddBook{
public:
AddBook()
{
count=0;
}
void AddEntry();
void DispAll();
void DispEntry(int i); // Displays one entry
void SearchLast();
int Menu();
struct EntryStruct
{
char FirstName[15];
char LastName[15];
char Birthday[15];
char PhoneNum[15];
char Email[15];
};
EntryStruct entries[100];
int count;
};
void AddBook::AddEntry()
{
cout << "Enter First Name: ";
cin >> entries[count].FirstName;
cout << "Enter Last Name: ";
cin >> entries[count].LastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
cout << "Enter Email: ";
cin >> entries[count].Email;
++count;
}
void AddBook::DispEntry(int i)
{
cout << "First name : " << entries[i].FirstName << endl;
cout << "Last name : " << entries[i].LastName << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
}
void AddBook::DispAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DispEntry(i);
}
void AddBook::SearchLast()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].LastName) == 0)
{
cout << "Found ";
DispEntry(i);
cout << endl;
}
}
}
AddBook AddressBook;
int Menu()
{
int num;
bool BoolQuit = false;
while(BoolQuit == false)
{
cout << "Address Book Menu" << endl;
cout << "(1) Add A New Contact" << endl;
cout << "(2) Search By Last Name" << endl;
cout << "(3) Show Complete List" << endl;
cout << "(4) Exit And Save" << endl;
cout << endl;
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
return 0;
}
int main (){
Menu();
return 0;
}
As it currently stands, I'm still stuck. Here's where I believe I should start:
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
//save first name
//save last name
//save dob
//save phone number
//save email
//exit
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
Somehow, during menu option 4 the array should dump the data into a .txt file and arrange it in a way that it can be easily imported upon reloading the program. I'm a little confused as to how I can store the array data from each character array into a .txt file.
Well first, if the input is coming from the file input, then instead of doing cin >> x you would have to do input >> x. If it's coming from standard input (the keyboard), then you can use cin.
Also, your else if statement should be something like this:
while (true)
{
// ...
else if (num == 4)
{
for (int i = 0; i < AddressBook.count; ++i)
{
AddBook::EntryStruct data = AddressBook.entries[i];
out << data.FirstName << " " << data.LastName
<< std::endl
<< data.Birthday << std::endl
<< data.PhoneNum << std::endl
<< data.Email;
}
}
break;
}
The purpose of the following code is to take user input of 6 movie titles and realease dates, write that data to a file using fstream, then read the data into 2 string characters (line1 and line2) in a loop, such that the first loop will assign line1 and line2 the first movie title and year, and the second loop will assign line1 and 2 the 2nd movie title and year, and so on, until eof.
// array of structures
#include <iostream>
#include <string>
#include <sstream>
#include <istream>
#include <stdio.h>
#include <cctype>
#include <fstream>
#include <cassert>
#include <assert.h>
using namespace std;
#define NUM_MOVIES 6
struct movies_iit
{
string title;
int year;
}
films[NUM_MOVIES];
// global variables
char title[20], y, n;
int year;
string search;
// function 1
void sort_on_title(movies_iit films[], int n)
{
// Local struct variable used to swap records
movies_iit temp;
for (int i = 0; i < n - 1; i++)
{
for (int i = 0; i < n - 1; i++)
{
/* If s[i].title is later in alphabet than
s[i+1].title, swap the two records */
if (films[i].title > films[i + 1].title)
{
temp = films[i];
films[i] = films[i + 1];
films[i + 1] = temp;
}
}
}
}
//end function 1
//function query1 prototype
void query1(movies_iit movie);
// function query2 prototype
void query2(movies_iit movie);
// function 2 prototype
void printmovie(movies_iit movie);
int main()
{
// login
// username: user
// password: word
string mystr, pass, name, line1, line2;
int n;
char response;
// output object
ofstream fout("data.dat");
// input object
ifstream fin("data.dat");
assert(fin.is_open());
cout << "enter your username " << endl;
cin >> name;
cout << "enter your password " << endl;
cin >> pass;
cout << "\n" << endl;
if (name == "user" && pass == "word")
cout << "Welcome, user." << endl;
else
{
cout << "###" << "unrecognized username/password combination" << "\t" << "please try again" << "###" << endl;
system("PAUSE");
return 0;
}
cin.ignore(std::numeric_limits < std::streamsize > ::max(), '\n');
cout << "\n" << endl;
for (n = 0; n < NUM_MOVIES; n++)
{
cout << "Enter title: ";
getline(cin, films[n].title);
cout << "Enter year: ";
getline(cin, mystr);
stringstream(mystr) >> films[n].year;
}
cout << "\n" << endl;
for (int i = 0; i < NUM_MOVIES; ++i)
{
fout << films[i].title << "\n";
fout << films[i].year << "\n";
}
// sort records, function 1 call
sort_on_title(films, NUM_MOVIES);
cout << "\nYou have entered these movies:\n";
for (n = 0; n < NUM_MOVIES; n++)
printmovie(films[n]); // function 2 call
cout << "Perform an alphabetical search? (y/n)" << endl;
cin >> response;
if (response == 'y')
{
cout << "Please enter title" << endl;
cin >> title;
if (fin)
{
getline(fin, line1); // read first 2 recs
getline(fin, line2);
while (fin) // keep reading till the eof
{
if (line1 == "title")
{
cout << " >> " << line1 << endl;
cout << line2 << endl;
}
else
{
cout << line1 << endl;
cout << line2 << endl;
}
}
}
fin.close(); //close input file
response == n;
}
else if (response == 'n')
cout << "\n" << endl;
else
cout << "invalid entry" << endl;
cout << "\n" << endl;
}
// function 2 definition
void printmovie(movies_iit movie)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
// function query1 defintion
void query1(movies_iit movie)
{
if (movie.title == "title")
{
cout << " >> " << movie.title;
cout << " (" << movie.year << ")\n";
}
else
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
}
// function query2 definition
void query2(movies_iit movie)
{
if (movie.year >= year)
{
cout << movie.title;
cout << " (" << movie.year << ")\n";
}
}
In the loop where I read values from the file into my strings, in my output it does not display the data stored in the strings. Why is that, and how can I fix the issue?
I realized that the code I originally posted didn't work; here is a functional one.
You need to close the 'fout' filestream before you try to read from it using 'fin'.
fout.close(); // <== Close the output file to flush the buffered I/O
The data you are writing to the file is likely buffered (not written to the file immediately). Your data.dat file is empty when you try to read it during your search.
Close the file in which data is being stored.
You are matching for string "title" and not input which user has provided.
getline() should be inside while loop ( as you want to match all the lines and not just 1st 2 records)
int main (){
//login
//username: user
//password: word
string mystr, pass, name, line1, line2;
int n;
char response;
//output object
ofstream fout ("data.dat");
//input object
cout << "enter your username "<<endl;
cin >> name;
cout << "enter your password "<<endl;
cin >> pass;
cout << "\n" << endl;
if (name == "user" && pass == "word")
cout << "Welcome, user." << endl;
else
{cout << "###" << "unrecognized username/password combination" << "\t" << "please try again" << "###" << endl;
//system("PAUSE");
return 0;
}
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << "\n" << endl;
for (n=0; n<NUM_MOVIES; n++)
{
cout << "Enter title: ";
getline (cin,films[n].title);
cout << "Enter year: ";
getline (cin,mystr);
stringstream(mystr) >> films[n].year;
}
cout << "\n" << endl;
//###################################################################################################################
//write to file
//###################################################################################################################
for (int i = 0; i < NUM_MOVIES; ++i)
{
fout << films[i].title << "\n";
fout << films[i].year << "\n";
}
fout.close();
//sort records, function 1 call
sort_on_title(films, NUM_MOVIES);
cout << "\nYou have entered these movies:\n";
for (n=0; n<NUM_MOVIES; n++)
printmovie (films[n]); //function 2 call
ifstream fin("data.dat");
assert(fin.is_open());
//###################################################################################################################
//query 1
//###################################################################################################################
cout << "Perform an alphabetical search? (y/n)" << endl;
cin >> response;
if (response == 'y')
{cout << "Please enter title" << endl;
cin >> title;
if (fin.good())
{
while(!fin.eof()) //keep reading till the eof
{
getline(fin,line1); // read first 2 recs
if(!fin.eof())
getline(fin,line2);
if (line1 == title)
{
cout << " >> " << line1 << endl;
cout << line2 << endl;
}
// else
// {
// cout << line1 << endl;
// cout << line2 << endl;
// }
}
}
fin.close(); //close input file
response == n;
}
else if (response == 'n')
cout << "\n" << endl;
else
cout << "invalid entry" << endl;
cout << "\n" << endl;
}