I am making a program that takes info from a file then puts it into a struct then makes an array of structs. I have the program done, but when I compile I get 2 errors. "Expected Declaration" and "Syntax Error: Constant" both pointing to the first line of the read in file. I am at a loss and I am not sure how to get it running. My code I am using looks like this:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct book
{
int ISBN;
string Author;
string Title;
int Quantity;
double price;
};
void choice1(book books[], int& size, int MAX_SIZE)
{
ifstream inFile;
inFile.open("Inventory.txt");
string str;
while (inFile && size < MAX_SIZE)
{
getline(inFile, str);
books[size].ISBN = atoi(str.c_str());
getline(inFile, books[size].Author);
getline(inFile, books[size].Title);
getline(inFile, str);
books[size].Quantity = atoi(str.c_str());
getline(inFile, str);
books[size].price = atoi(str.c_str());
getline(inFile, str);
size++;
}
cout << "You have successfully read the file." << endl;
inFile.close();
}
void choice2(book books[], int size)
{
for (int i = 0; i < size; i++)
{
cout << endl;
cout << "Book Number: " << (i + 1) << endl;
cout << "ISBN: " << books[i].ISBN << endl;
cout << "Author: " << books[i].Author << endl;
cout << "Title: " << books[i].Title << endl;
cout << "Quantity: " << books[i].Quantity << endl;
cout << "Price: $" << books[i].price << endl;
}
if (size != 0)
cout << "You have successfully printed the array." << endl;
else
cout << "Array is empty. Read the file first." << endl;
}
void choice3(book books[], int size)
{
if (size == 0)
cout << "Array is empty. Read the data first." << endl;
else
{
int isbn;
int option;
int qty;
cout << "\nEnter the ISBN of the book: ";
cin >> isbn;
cout << "1. Increment" << endl;
cout << "2. Decrement" << endl;
cout << "3. Add New" << endl;
cout << "Enter your option: ";
cin >> option;
cout << "Enter the quantity: ";
cin >> qty;
for (int i = 0; i < size; i++)
{
if (books[i].ISBN == isbn)
{
if (option == 1)
books[i].Quantity += qty;
else if (option == 2)
{
books[i].Quantity -= qty;
if (books[i].Quantity)
books[i].Quantity = 0;
}
else if (option == 3)
books[i].Quantity = qty;
break;
}
}
cout << "You have successfully updated the array." << endl;
}
}
void choice4(book books[], int& size, int MAX_SIZE)
{
if (size < MAX_SIZE)
{
string str;
cout << "\nEnter the book ISBN: ";
cin >> books[size].ISBN;
cout << "Enter the author name: ";
cin >> books[size].Author;
cout << "Enter the book tile: ";
cin >> books[size].Title;
cin.get();
cout << "Enter the books quantity: ";
cin >> books[size].Quantity;
cout << "Enter the book price: $";
cin >> books[size].price;
size++;
cout << "You have successfully inserted an entry." << endl;
}
}
void choice5(book books[], int size)
{
for (int i = 1; i < size; i++)
{
book current = books[i];
int j = i;
while (j > 0 && (books[j - 1].Title).compare(current.Title) > 0)
{
books[j] = books[j - 1];
j--;
}
books[j] = current;
}
if (size != 0)
cout << "You have successfully sorted the array." << endl;
else
cout << "Array is empty. Read the data first." << endl;
}
void choice6(book books[], int& size)
{
if (size == 0)
cout << "Array is empty. Read the data first." << endl;
else
{
int isbn;
cout << "\nEnter the ISBN of the book: ";
cin >> isbn;
for (int i = 0; i < size; i++)
{
if (books[i].ISBN == isbn)
{
int j = i;
while (j < size - 1)
{
books[j] = books[j + 1];
j++;
}
size--;
break;
}
}
cout << "You have successfully deleted an entry." << endl;
}
}
void choice7(book books[], int size)
{
ofstream outFile;
outFile.open("finalData.dat");
for (int i = 0; i < size; i++)
{
outFile << "Book Number: " << (i + 1) << endl;
outFile << "ISBN: " << books[i].ISBN << endl;
outFile << "Author: " << books[i].Author << endl;
outFile << "Title: " << books[i].Title << endl;
outFile << "Quantity: " << books[i].Quantity << endl;
outFile << "Price: $" << books[i].price << endl << endl;
}
if (size != 0)
cout << "You have successfully printed the array." << endl;
else
cout << "Array is empty. Read the file first." << endl;
outFile.close();
}
// File: Boookstore.cpp
#include<iostream>
#include"Inventory.txt"
using namespace std;
int main()
{
const int MAX_SIZE = 100;
int size = 0;
int choice;
book books[MAX_SIZE];
do
{
cout << "1: Read inventory forn file" << endl;
cout << "2: Display Inventory" << endl;
cout << "3: Update an entry" << endl;
cout << "4: Add an entry" << endl;
cout << "5: Sort inventory" << endl;
cout << "6: Delete an entry" << endl;
cout << "7: Write inventory to file and exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch (choice)
{
case 1:
choice1(books, size, MAX_SIZE);
break;
case 2:
choice2(books, size);
break;
case 3:
choice3(books, size);
break;
case 4:
choice4(books, size, MAX_SIZE);
break;
case 5:
choice5(books, size);
break;
case 6:
choice6(books, size);
break;
case 7:
choice7(books, size);
cout << "Thank you." << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
cout << endl;
} while (choice != 7);
system("pause");
return 0;
}
I have the read in file in the same folder as my source file, but I am not sure what is causing the issue. My read in file is exactly this:
20451
My First Book
Mark Lusk
Pearson Publishing
40
45.34
9780316
Brown Family
Mason Victor
Little Brown
36
105.99
1349877
Story of My Life
Norah M Jones
CreateSpace Independent Publishing Platform
20
18
It is supposed to take the first line of the file and set it as an int to the ISNB section of my struct, but it just keeps telling me it is a constant. Any help is appreciated!
You can't #include a data file. It will treat it like part of your code - and it's obviously not valid c++.
#include "Inventory.txt"
You have to open the file and read it with things like ifstream.
Related
Sorry in advance if this is lengthy. the problem is within line 9. (where the 2nd cout is.) apparently, but i'm new to this so I can't identify exactly what the issue is.
#include <iostream>
#include <vector>
using namespace std;
void outputRoster(const vector<int> &jersey, const vector<int> &ratings) {
cout << "ROSTER" << endl;
for (int i =1; i < jersey.size(); ++i) {
cout << "Player " << i << " -- Jersey number: " << jersey.at(i-1) << ", Rating: " << ratings << endl;
}
cout << endl;
}
void addPlayer(vector<int> &jersey, vector<int> &ratings) {
int num;
cout << "Enter another player's jersey number: ";
cin >> num;
jersey.push_back(num);
cout << "Enter another player's ratings: ";
cin >> num;
cout << endl;
ratings.push_back(num);
}
void removePlayer(vector<int> &jersey, vector<int> &ratings) {
int num;
cout << "Enter a jersey number: ";
cin >> num;
cout << endl;
for (int i = 0; i < jersey.size(); ++i){
if (jersey.at(i)==num){
jersey.erase(jersey.begin()+i);
ratings.erase(ratings.begin()+i);
break;
}
}
}
void updatePlayerRating(const vector<int> &jersey, vector<int> &ratings){
int num;
cout << "Enter a jersey number: " << endl;
cin >> num;
for (int i = 0; i < jersey.size(); ++i){
if(jersey.at(i) == num){
cout << "Enter a new rating for player: ";
cin >> num;
cout << endl;
ratings.at(i) = num;
}
}
}
void outputPlayersAboveRating(const vector<int> &jersey, const vector<int> &ratings) {
int num;
cout << "Enter a rating: ";
cin >> num;
cout << endl;
cout << "ABOVE " << num << endl;
for (int i = 0; i < ratings.size(); ++i){
if (ratings.at(i) > num) {
cout << "Player " << i+1 << " -- Jersey number: " << jersey.at(i) << ", Rating: " << ratings.at(i);
}
}
cout << endl;
}
int main() {
vector<int> jersey;
vector<int> ratings;
for (int i = 0; i < 5; ++i) {
int num;
cout << "Enter player " << i+1 << "'s jersey number:";
cin >> num;
jersey.push_back(num);
cout << "Enter player " << i+1 << "'s ratings:";
cin >> num;
ratings.push_back(num);
cout << endl;
cout << endl;
}
outputRoster(jersey, ratings);
char inp;
while(true) {
cout << "MENU" << endl;
cout << "a - Add player" << endl;
cout << "d - Remove player" << endl;
cout << "u - Update player rating" << endl;
cout << "r - Output players above a rating" << endl;
cout << "o - Output roster" << endl;
cout << "q - Quit" << endl;
cout << "Choose an option: ";
cin >> inp;
cout << endl;
if (inp == 'a') {
addPlayer(jersey, ratings);
}
else if (inp == 'd') {
removePlayer(jersey, ratings);
}
else if (inp == 'u') {
updatePlayerRating(jersey, ratings);
}
else if (inp == 'r') {
outputPlayersAboveRating(jersey, ratings);
}
else if (inp == 'o') {
outputRoster(jersey, ratings);
}
else if (inp == 'q') {
return 0;
}
}
return 0;
}
Any and all help is appreciated also if possible, could you explain how to avoid an error like this in the future.
Thanks in advance.
You cannot print ratings directly in
cout ... << ratings ... because std::vector doesn't have an operator overload for printing. Rather, you have to print out an element inside that vector, so change it to cout ... << ratings[i] ..., which I'm assuming is your desired effect.
This is exactly what the compiler error is telling you. std::vector doesn't have an overload (no operator<< match).
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;
});
I am really stumped on this one. I am making a program that takes info in from a file and then puts it into structs and then the structs into arrays. My problem appears to come after I compile. I do not show any errors in the code itself, but the error comes up as the first line of the read in file.
My Code is as follows:
// File: Inventory.txt
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct book
{
int ISBN;
string Author;
string Title;
int Quantity;
double price;
};
void choice1(book books[], int& size, int MAX_SIZE)
{
ifstream inFile;
inFile.open("inventory.txt");
string str;
while(inFile && size < MAX_SIZE)
{
getline(inFile, str);
books[size].ISBN = atoi(str.c_str());
getline(inFile, books[size].Author);
getline(inFile, books[size].Title);
getline(inFile, str);
books[size].Quantity = atoi(str.c_str());
getline(inFile, str);
books[size].price = atoi(str.c_str());
getline(inFile, str);
size++;
}
cout << "You have successfully read the file." << endl;
inFile.close();
}
void choice2(book books[], int size)
{
for(int i = 0; i < size; i++)
{
cout << endl;
cout << "Book Number: " << (i + 1) << endl;
cout << "ISBN: " << books[i].ISBN << endl;
cout << "Author: " << books[i].Author << endl;
cout << "Title: " << books[i].Title << endl;
cout << "Quantity: " << books[i].Quantity << endl;
cout << "Price: $" << books[i].price << endl;
}
if(size != 0)
cout << "You have successfully printed the array." << endl;
else
cout << "Array is empty. Read the file first." << endl;
}
void choice3(book books[], int size)
{
if(size == 0)
cout << "Array is empty. Read the data first." << endl;
else
{
int isbn;
int option;
int qty;
cout << "\nEnter the ISBN of the book: ";
cin >> isbn;
cout << "1. Increment" << endl;
cout << "2. Decrement" << endl;
cout << "3. Add New" << endl;
cout << "Enter your option: ";
cin >> option;
cout << "Enter the quantity: ";
cin >> qty;
for(int i = 0; i < size; i++)
{
if(books[i].ISBN == isbn)
{
if(option == 1)
books[i].Quantity += qty;
else if(option == 2)
{
books[i].Quantity -= qty;
if(books[i].Quantity)
books[i].Quantity = 0;
}
else if(option == 3)
books[i].Quantity = qty;
break;
}
}
cout << "You have successfully updated the array." << endl;
}
}
void choice4(book books[], int& size, int MAX_SIZE)
{
if(size < MAX_SIZE)
{
string str;
cout << "\nEnter the book ISBN: ";
cin >> books[size].ISBN;
cout << "Enter the author name: ";
cin >> books[size].Author;
cout << "Enter the book tile: ";
cin >> books[size].Title;
cin.get();
cout << "Enter the books quantity: ";
cin >> books[size].Quantity;
cout << "Enter the book price: $";
cin >> books[size].price;
size++;
cout << "You have successfully inserted an entry." << endl;
}
}
void choice5(book books[], int size)
{
for(int i = 1; i < size; i++)
{
book current = books[i];
int j = i;
while(j > 0 && (books[j - 1].Title).compare(current.Title) > 0)
{
books[j] = books[j - 1];
j--;
}
books[j] = current;
}
if(size != 0)
cout << "You have successfully sorted the array." << endl;
else
cout << "Array is empty. Read the data first." << endl;
}
void choice6(book books[], int& size)
{
if(size == 0)
cout << "Array is empty. Read the data first." << endl;
else
{
int isbn;
cout << "\nEnter the ISBN of the book: ";
cin >> isbn;
for(int i = 0; i < size; i++)
{
if(books[i].ISBN == isbn)
{
int j = i;
while(j < size - 1)
{
books[j] = books[j + 1];
j++;
}
size--;
break;
}
}
cout << "You have successfully deleted an entry." << endl;
}
}
void choice7(book books[], int size)
{
ofstream outFile;
outFile.open("finalData.dat");
for(int i = 0; i < size; i++)
{
outFile << "Book Number: " << (i + 1) << endl;
outFile << "ISBN: " << books[i].ISBN << endl;
outFile << "Author: " << books[i].Author << endl;
outFile << "Title: " << books[i].Title << endl;
outFile << "Quantity: " << books[i].Quantity << endl;
outFile << "Price: $" << books[i].price << endl << endl;
}
if(size != 0)
cout << "You have successfully printed the array." << endl;
else
cout << "Array is empty. Read the file first." << endl;
outFile.close();
}
// File: Boookstore.cpp
#include<iostream>
#include"inventory.txt"
using namespace std;
int main()
{
const int MAX_SIZE = 100;
int size = 0;
int choice;
book books[MAX_SIZE];
do
{
cout << "1: Read inventory forn file" << endl;
cout << "2: Display Inventory" << endl;
cout << "3: Update an entry" << endl;
cout << "4: Add an entry" << endl;
cout << "5: Sort inventory" << endl;
cout << "6: Delete an entry" << endl;
cout << "7: Write inventory to file and exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
switch(choice)
{
case 1:
choice1(books, size, MAX_SIZE);
break;
case 2:
choice2(books, size);
break;
case 3:
choice3(books, size);
break;
case 4:
choice4(books, size, MAX_SIZE);
break;
case 5:
choice5(books, size);
break;
case 6:
choice6(books, size);
break;
case 7:
choice7(books, size);
cout << "Thank you." << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
cout << endl;
}while(choice != 7);
system("pause");
return 0;
}
My Read in file (inventory.txt) is:
20451 <<The line that give the expected unqualified-id before numeric constant error
My First Book
Mark Lusk
Pearson Publishing
40
45.34
9780316
Brown Family
Mason Victor
Little Brown
36
105.99
1349877
Story of My Life
Norah M Jones
CreateSpace Independent Publishing Platform
20
18
I have been looking at my code for days and cannot find why I am getting this error! I do apologize if the answer is staring me in the face, but I could not find anything about getting this error from the file not the code. Any advise would be much appreciated!
This #include"inventory.txt" should probably be something like #include "inventory.h" if that header file exists.
// File: Boookstore.cpp
#include<iostream>
#include"inventory.txt"
Every time I do anything, and my while(1) gets called in my main function, my file gets cleared. It's driving me crazy. I've tried EVERYTHING. I try to put my ofstream out("data.dat"); outside the while(1) statement so it isn't called everytime but then nothing is written to the file like the ofstream isn't even working!
I've tried to make the ofstream static, so it isn't called over and over again like:
static ofstream open("data.dat");
That doesn't work.
And like I said, when I put the ofstream OUTSIDE the while statement, nothing is written to the file. Like:
ofstream out("data.dat");
while (1)
{
string line = "";
cout << "There are currently " << structList.size() << " items in memory.";
cout << endl << endl;
cout << "Commands: " << endl;
cout << "1: Add a new record " << endl;
cout << "2: Display a record " << endl;
cout << "3: Edit a current record " << endl;
cout << "4: Delete a record " << endl;
cout << "5: Save current information " << endl;
cout << "6: Exit the program " << endl;
cout << endl;
cout << "Enter a command 1-6: ";
getline(cin , line);
int rValue = atoi(line.c_str());
system("cls");
switch (rValue)
{
case 1:
structList = addItem(structList);
break;
case 2:
displayRecord(structList);
break;
case 3:
structList = editRecord(structList);
break;
case 4:
deleteRecord(structList);
break;
case 5:
if (!structList.size()) { cout << "There are no items to save! Enter one first!" << endl << endl; system("pause"); system("cls"); break; }
writeVector(out , structList);
break;
case 6:
return 0;
default:
cout << "Command invalid. You can only enter a command number 1 - 6. Try again. " << endl;
}
out.close();
}
And can someone tell me why my check to prevent reading of a empty file won't work?
My Check:
bool checkFileEmpty()
{
ifstream in("data.dat");
if (in.peek() == in.eofbit)
{
return true;
}
return false;
}
I am so sick and tired of my program crashing on startup over and over again because my vector is getting set to a size of 200 million. I've tried a BUNCH of stuff for this... none of it works... Please GOD someone help me with both of these! I've been up for 18 hours working on this ( all night yes ) and i'm ALMOST done. I'm begging you....
My Code:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace System;
using namespace std;
#pragma hdrstop
bool isValidChoice(int size, int choice);
bool checkFileEmpty();
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);
template<typename T>
vector<T> readVector(ifstream &in);
template<typename T>
vector<T> addItem(vector<T> &vec);
template<typename T>
void printItemDescriptions(vector<T> &vec);
template<typename T>
int displayRecord(vector<T> &vec);
template<typename T>
vector<T> editRecord(vector<T> &vec);
template<typename T>
vector<T> deleteRecord(vector<T> &vec);
struct InventoryItem {
string Description;
int Quantity;
int wholesaleCost;
int retailCost;
string dateAdded;
} ;
int main(void)
{
cout << "Welcome to the Inventory Manager extreme! [Version 1.0]" << endl;
ifstream in("data.dat");
if (in.is_open()) { cout << "File \'data.dat\' has been opened successfully." << endl; } else { cout << "Error opening data.dat" << endl;}
cout << "Loading data..." << endl;
vector<InventoryItem> structList = readVector<InventoryItem>( in );
cout <<"Load complete." << endl << endl;
in.close();
while (1)
{
string line = "";
cout << "There are currently " << structList.size() << " items in memory.";
cout << endl << endl;
cout << "Commands: " << endl;
cout << "1: Add a new record " << endl;
cout << "2: Display a record " << endl;
cout << "3: Edit a current record " << endl;
cout << "4: Delete a record " << endl;
cout << "5: Save current information " << endl;
cout << "6: Exit the program " << endl;
cout << endl;
cout << "Enter a command 1-6: ";
getline(cin , line);
int rValue = atoi(line.c_str());
system("cls");
ofstream out("data.dat");
switch (rValue)
{
case 1:
structList = addItem(structList);
break;
case 2:
displayRecord(structList);
break;
case 3:
structList = editRecord(structList);
break;
case 4:
deleteRecord(structList);
break;
case 5:
if (!structList.size()) { cout << "There are no items to save! Enter one first!" << endl << endl; system("pause"); system("cls"); break; }
writeVector(out , structList);
break;
case 6:
return 0;
default:
cout << "Command invalid. You can only enter a command number 1 - 6. Try again. " << endl;
}
out.close();
}
system("pause");
return 0;
}
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
out << vec.size();
for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
{
out << *i;
}
cout << "Save completed!" << endl << endl;
}
ostream &operator<<(ostream &out, const InventoryItem &i)
{
out << i.Description << ' ';
out << i.Quantity << ' ';
out << i.wholesaleCost << ' ' << i.retailCost << ' ';
out << i.dateAdded << ' ';
return out;
}
istream &operator>>(istream &in, InventoryItem &i)
{
in >> i.Description;
in >> i.Quantity;
in >> i.wholesaleCost >> i.retailCost;
in >> i.dateAdded;
return in;
}
template<typename T>
vector<T> readVector(ifstream &in)
{
size_t size;
if (checkFileEmpty())
{
size = 0;
} else {
in >> size;
}
vector<T> vec;
vec.reserve(size);
for(unsigned int i = 0; i < size; i++)
{
T tmp;
in >> tmp;
vec.push_back(tmp);
}
return vec;
}
template<typename T>
vector<T> addItem(vector<T> &vec)
{
system("cls");
string word;
unsigned int number;
InventoryItem newItem;
cout << "-Add a new item-" << endl << endl;
cout << "Enter the description for the item: ";
getline (cin , word);
newItem.Description = word;
cout << endl;
cout << "Enter the quantity on hand for the item: ";
getline (cin , word);
number = atoi(word.c_str());
newItem.Quantity = number;
cout << endl;
cout << "Enter the Retail Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
newItem.retailCost = number;
cout << endl;
cout << "Enter the Wholesale Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
newItem.wholesaleCost = number;
cout << endl;
cout << "Enter current date: ";
getline (cin , word);
newItem.dateAdded = word;
vec.push_back(newItem);
return vec;
}
template<typename T>
void printItemDescriptions(vector<T> &vec)
{
int size = vec.size();
if (size)
{
cout << "---------------------------------" << endl;
cout << "| ~ Item Descriptions ~ |" << endl;
cout << "---------------------------------" << endl;
cout << "*********************************" << endl;
for (int i = 0 ; i < size ; i++)
{
cout << "(" << i+1 << ")" << ": " << vec[i].Description << endl;
}
cout << "*********************************" << endl << endl;
}
}
template<typename T>
int displayRecord(vector<T> &vec)
{
string word = "";
string quit = "quit";
int choice = 1;
int size = vec.size();
if (size)
{
printItemDescriptions(vec);
cout << endl;
while (1)
{
cout << "Type \"exit\" to return to the Main Menu." << endl << endl;
cout << "Enter \"list\" to re-display the items." << endl << endl;
cout << endl;
cout << "Pick the number of the item you would like to display: ";
getline (cin , word);
if (convertToLower(word) == "exit") { system("cls"); return 0; }
if (convertToLower(word) == "list") { system("cls"); displayRecord(vec); }
choice = atoi(word.c_str());
choice -= 1;
if (isValidChoice(size, choice))
{
system("cls");
cout << endl << "[Item (" << choice << ") details] " << endl << endl;
cout << "******************" << endl;
cout << "* Description * " << vec[choice].Description << endl;
cout << "******************" << endl << endl;
cout << "******************" << endl;
cout << "*Quantity On Hand* " << vec[choice].Quantity << endl;
cout << "******************" << endl << endl;
cout << "******************" << endl;
cout << "* Wholesale Cost * " << vec[choice].wholesaleCost << endl;
cout << "****************** " << endl << endl;
cout << "******************" << endl;
cout << "* Retail Cost * " << vec[choice].retailCost << endl;
cout << "****************** " << endl << endl;
cout << "******************" << endl;
cout << "* Data Added * " << vec[choice].dateAdded << endl;
cout << "****************** " << endl << endl;
} else { system("cls"); cout << "That item doesn't exist!" << endl; cout << "Pick another item or enter \"list\" to see available items." << endl << endl; }
}
} else { cout << "There are currently no items to display." << endl << endl; system("pause"); system("cls"); return 0; }
return 1;
}
bool isValidChoice(int size, int choice)
{
for (int i = 0 ; i <= size ; i++)
{
if (choice == i) { return true; }
}
return false;
}
string convertToLower(string word)
{
for (unsigned int i = 0 ; i < word.size() ; i++)
{
word[i] = tolower(word[i]);
}
return word;
}
bool checkFileEmpty()
{
ifstream in("data.dat");
if (in.peek() == in.eofbit)
{
return true;
}
return false;
}
template<typename T>
vector<T> editRecord(vector<T> &vec)
{
string word;
int choice;
printItemDescriptions(vec);
cout << "Choose item to edit: ";
getline ( cin, word );
choice = atoi(word.c_str());
system("cls");
unsigned int number;
InventoryItem newItem;
cout << "-Edit an item-" << endl << endl;
cout << "Enter the description for the item: ";
getline (cin , word);
vec[choice-1].Description = word;
cout << endl;
cout << "Enter the quantity on hand for the item: ";
getline (cin , word);
number = atoi(word.c_str());
vec[choice-1].Quantity = number;
cout << endl;
cout << "Enter the Retail Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
vec[choice-1].retailCost = number;
cout << endl;
cout << "Enter the Wholesale Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
vec[choice-1].wholesaleCost = number;
cout << endl;
cout << "Enter current date: ";
getline (cin , word);
vec[choice-1].dateAdded = word;
system("cls");
cout << "Item edited successfully! " << endl;
return vec;
}
template<typename T>
vector<T> deleteRecord(vector<T> &vec)
{
if (!vec.size()) { cout << "There are no items to delete!" << endl << endl; return vec; }
printItemDescriptions(vec);
string word;
int choice;
cout << "Choose item to delete: ";
getline( cin, word);
choice = atoi(word.c_str());
vec.erase (vec.begin()+choice-1);
return vec;
}
You'd better move the ofstream openning and closing inside case 5.
Here you create a new file at each while iteration.
case 5:
{
ofstream out("data.dat");
writeVector(out , structList);
out.close();
}
break;
ofstream out("data.dat");
Opens the file for writing. By default, it will start at the very beginning wiping out anything that was there previously. First, use a different output file than the file you are reading from.
Try adding the close to the case 6 statements:
case 6:
out.close();
return 0;
I'm pretty sure the close isn't getting called as the return will exit main before getting to that statement. With the file unclosed you are left with a buffer unflushed and I suspect that will leave the data unwritten.
You should move the open to before the while loop and also remove the out.close() from the while loop as it's going to close the file after the first menu selection.
To check if a file is empty or cannot be opened
bool IsEmpty( const std::string & filename ) {
std::ifstream ifs( filename.c_str() );
if ( ifs.is_open() ) {
std::string line;
return ! std::getline( ifs, line );
}
else {
return true;
}
}