string read from file won't display in loop - c++

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;
}

Related

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

Confusing Syntax Error

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.

C++ Input Into Structure: _getch()

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;

Mixing formatted input extractors with getline causes cout display to stick together

The following code seves to establish a movie database and query through it. It works as intended except for the first cout statements being clumped together. The code is as follows.
// array of structures
#include <iostream>
#include <string>
#include <sstream>
#include <stdio.h>
#include <cctype>
using namespace std;
#define NUM_MOVIES 6
//structure
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);
//beginning of main
int main ()
{
//login
//username: user
//password: word
string mystr;
int n;
char response;
string pass;
string name;
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;
}
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;
}
//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
//Query 1
cout << "Perform an alphabetical search? (y/n)" << endl;
cin >> response;
if (response == 'y')
{cout << "Please enter title" << endl;
cin >> title;
for (n=0; n<NUM_MOVIES; n++)
{query1 (films[n]);
response == n;
}
}
else if (response == 'n')
cout << "\n" << endl;
else
cout << "invalid entry" << endl;
//Query 2
cout << "Perform a chronological search? (y/n)" << endl;
cin >> response;
//greater than
if (response == 'y')
{ cout << "greater than what year?" << endl;
cin >> year;
for (n=0; n<NUM_MOVIES; n++)
{ query2 (films[n]);
}
}
else if (response == 'n')
cout << "Thank you, goodbye." << endl;
else
cout << "invalid entry" << endl;
system("pause");
return 0;
}
//end of main
//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";
}
}
I managed to trace the problem back to the login at the beginning of the code, without the
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;
}
section, the code works fine. Why is the beginning of my code sticking together, and how can I fix it without omitting the login?
cin >> pass stops reading at the whitespace, but it is still there in the buffer. When you call getline it sees the newline waiting in the buffer and returns. You need to empty the buffer before you call getline.
See: http://en.cppreference.com/w/cpp/io/manip/ws
It also looks like you have an error here:
for (n=0; n<NUM_MOVIES; n++)
{query1 (films[n]);
response == n;
}
Should that be response = n? As it stands that statement has no utility.