How should I make my C++ code shorter without using arrays? - c++

I'm currently working on an exercise given to me by my university professor and one of the questions is to create a program using data structures which inputs data of any topic and outputs them in a neat format. The problem is the question specifically states to not use arrays, and shorter codes grants bonus marks. How should I shorten my code below?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct musicRecord //structure name
{
//structure members
string title;
string artist;
string album;
string genre;
string releaseYear;
};
int main()
{
int numRecords;
musicRecord music1, music2, music3, music4, music5; //structure variables
//input
cout << "===================================================";
cout << "\nRecord No. 1"<< endl;
cout << "\nEnter the title : ";
getline(cin, music1.title);
cout << "\nEnter the artist's name : ";
getline(cin, music1.artist);
cout << "\nEnter the album name : ";
getline(cin, music1.album);
cout << "\nEnter the genre of the title : ";
getline(cin, music1.genre);
cout << "\nEnter the year the title was released : ";
getline(cin, music1.releaseYear);
cout << endl << "===================================================";
cout << "\nRecord No. 2" << endl;
cout << "\nEnter the title : ";
getline(cin, music2.title);
cout << "\nEnter the artist's name : ";
getline(cin, music2.artist);
cout << "\nEnter the album name : ";
getline(cin, music2.album);
cout << "\nEnter the genre of the title : ";
getline(cin, music2.genre);
cout << "\nEnter the year the title was released : ";
getline(cin, music2.releaseYear);
cout << endl << "===================================================";
cout << "\nRecord No. 3" << endl;
cout << "\nEnter the title : ";
getline(cin, music3.title);
cout << "\nEnter the artist's name : ";
getline(cin, music3.artist);
cout << "\nEnter the album name : ";
getline(cin, music3.album);
cout << "\nEnter the genre of the title : ";
getline(cin, music3.genre);
cout << "\nEnter the year the title was released : ";
getline(cin, music3.releaseYear);
cout << endl << "===================================================";
cout << "\nRecord No. 4" << endl;
cout << "\nEnter the title : ";
getline(cin, music4.title);
cout << "\nEnter the artist's name : ";
getline(cin, music4.artist);
cout << "\nEnter the album name : ";
getline(cin, music4.album);
cout << "\nEnter the genre of the title : ";
getline(cin, music4.genre);
cout << "\nEnter the year the title was released : ";
getline(cin, music4.releaseYear);
cout << endl << "===================================================";
cout << "\nRecord No. 5" << endl;
cout << "\nEnter the title : ";
getline(cin, music5.title);
cout << "\nEnter the artist's name : ";
getline(cin, music5.artist);
cout << "\nEnter the album name : ";
getline(cin, music5.album);
cout << "\nEnter the genre of the title : ";
getline(cin, music5.genre);
cout << "\nEnter the year the title was released : ";
getline(cin, music5.releaseYear);
//output
cout << endl << "================================================================================================================";
cout << endl << "\t\t\t\t\t\tMUSIC RECORDS";
cout << endl << "================================================================================================================";
cout << endl << setw(5) << "Record No. |" << setw(10) << " Title" << setw(25) << "| Artist " << setw(20) << "| Album " << setw(20) << "| Genre " << setw(25) << "| Release Year |";
cout << endl << "----------------------------------------------------------------------------------------------------------------";
cout << endl << setw(12) << left << " 1";
cout << setw(27) << left << music1.title;
cout << setw(21) << left << music1.artist;
cout << setw(20) << left << music1.album;
cout << setw(20) << left << music1.genre;
cout << setw(15) << left << music1.releaseYear;
cout << endl << "----------------------------------------------------------------------------------------------------------------";
cout << endl << setw(12) << left << " 2";
cout << setw(27) << left << music2.title;
cout << setw(21) << left << music2.artist;
cout << setw(20) << left << music2.album;
cout << setw(20) << left << music2.genre;
cout << setw(15) << left << music2.releaseYear;
cout << endl << "----------------------------------------------------------------------------------------------------------------";
cout << endl << setw(12) << left << " 3";
cout << setw(27) << left << music3.title;
cout << setw(21) << left << music3.artist;
cout << setw(20) << left << music3.album;
cout << setw(20) << left << music3.genre;
cout << setw(15) << left << music3.releaseYear;
cout << endl << "----------------------------------------------------------------------------------------------------------------";
cout << endl << setw(12) << left << " 4";
cout << setw(27) << left << music4.title;
cout << setw(21) << left << music4.artist;
cout << setw(20) << left << music4.album;
cout << setw(20) << left << music4.genre;
cout << setw(15) << left << music4.releaseYear;
cout << endl << "----------------------------------------------------------------------------------------------------------------";
cout << endl << setw(12) << left << " 5";
cout << setw(27) << left << music5.title;
cout << setw(21) << left << music5.artist;
cout << setw(20) << left << music5.album;
cout << setw(20) << left << music5.genre;
cout << setw(15) << left << music5.releaseYear;
cout << endl << "================================================================================================================";
cout << endl << "\t\t\t\t\tEND OF PROGRAM, THANK YOU";
cout << endl << "================================================================================================================";
return 0;
}

As you might notice, you copy/paste code for each of your variables.
So create function to avoid to duplicate code, for example:
musicRecord inputMusicRecord(int recordNb)
{
musicRecord res;
cout << "===================================================";
cout << "\nRecord No. " << recordNb << endl;
cout << "\nEnter the title : ";
getline(cin, res.title);
cout << "\nEnter the artist's name : ";
getline(cin, res.artist);
cout << "\nEnter the album name : ";
getline(cin, res.album);
cout << "\nEnter the genre of the title : ";
getline(cin, res.genre);
cout << "\nEnter the year the title was released : ";
getline(cin, res.releaseYear);
return res;
}
void print(const musicRecord& music)
{
cout << endl << setw(12) << left << " 1";
cout << setw(27) << left << music.title;
cout << setw(21) << left << music.artist;
cout << setw(20) << left << music.album;
cout << setw(20) << left << music.genre;
cout << setw(15) << left << music.releaseYear;
}
And then, you might do:
void print_header()
{
cout << endl << "================================================================================================================";
cout << endl << "\t\t\t\t\t\tMUSIC RECORDS";
cout << endl << "================================================================================================================";
cout << endl << setw(5) << "Record No. |" << setw(10) << " Title" << setw(25) << "| Artist " << setw(20) << "| Album " << setw(20) << "| Genre " << setw(25) << "| Release Year |";
}
void print_separator()
{
cout << endl << "----------------------------------------------------------------------------------------------------------------";
}
void print_footer()
{
cout << endl << "================================================================================================================";
cout << endl << "\t\t\t\t\tEND OF PROGRAM, THANK YOU";
cout << endl << "================================================================================================================";
}
int main()
{
const musicRecord music1 = inputMusicRecord(1);
const musicRecord music2 = inputMusicRecord(2);
const musicRecord music3 = inputMusicRecord(3);
const musicRecord music4 = inputMusicRecord(4);
const musicRecord music5 = inputMusicRecord(5);
print_header();
print_separator();
print(music1);
print_separator();
print(music2);
print_separator();
print(music3);
print_separator();
print(music4);
print_separator();
print(music5);
print_footer();
}

Related

Calling while loop function in main function, and won't move past after completing loop

So, I'm creating a program for class to take orders of cookies, and the guideline is to create separate functions. Unfortunately, when I try to get into the subsequent functions, it doesn't seem to be doing that, and I was wondering where my problem may be at? I've tried playing around with parameters and data types and seeing if that would do anything, unfortunately I have come up short.
I appreciate all your help guys.
For people looking at this in the future, I've completed this program to work, and this first bit of code is the original code I was asking the question about... carry on to next portion.
#include <iostream>
using namespace std;
int getThinMints();
int getOreos();
int main(){
getThinMints();
getOreos();
return 0;
}
int getThinMints(){
int numThinMints;
int min_order = 0;
int max_order = 10;
while ((numThinMints < 0 || numThinMints > 10))
{
cout << "Enter the number of Thin Mints (0-10): ";
cin >> numThinMints;
cin.ignore(100, '\n');
cin.clear();
}
}
int getOreos(){
int numOreos;
int min_order = 0;
int max_order = 10;
while ((numOreos < 0 || numOreos > 10))
{
cout << "Enter the number of Thin Mints (0-10): ";
cin >> numOreos;
cin.ignore(100, '\n');
cin.clear();
}
}
New code I implemented for the complete program:
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
#include <iomanip>
using namespace std;
int getCookies(string cookietype, int max_order); // cookie input function prototype
int main()
{
int thin_mints;
int lemonUps;
int lemonades;
int samoas;
int tagalongs;
int dosidos;
int trefoils;
int thanksalot;
int toffee;
int caramel;
int max_order = 10; // 10 cookies max per type
int orderNumber = 0; // initial order number
double cPrice = 5.0; // $5 per order
string qtyStr = "(0-10): ";
string cookie1 = "Enter the number of Thin Mints " + qtyStr;
string cookie2 = "Enter the number of Lemon-Ups " + qtyStr;
string cookie3 = "Enter the number of Lemonades " + qtyStr;
string cookie4 = "Enter the number of Samoas " + qtyStr;
string cookie5 = "Enter the number of Tagalongs " + qtyStr;
string cookie6 = "Enter the number of Do-si-dos " + qtyStr;
string cookie7 = "Enter the number of Trefoils " + qtyStr;
string cookie8 = "Enter the number of Thanks-A-Lot " + qtyStr;
string cookie9 = "Enter the number of Toffee-tastic " + qtyStr;
string cookie10 = "Enter the number of Caramel Chocolate Chip " + qtyStr;
string fname, lname, address, cityStZip;
bool moreOrders = true;
ofstream outFile; // This will open a .txt file named 'na_orders' with an invoice for the cookie orders
// Open the output file
outFile.open ("na_orders.txt", ios::out);
while (moreOrders)
{
fname = lname = address = cityStZip = "";
cout << "Enter the customers first and last name (or q to quit): " <<endl;
cin >> fname;
if (fname == "q")
break;
orderNumber ++;
cin >> lname;
cin.ignore();
cin.clear();
while (address.length() == 0)
{
cout << "Enter the " << fname << " " << lname << "'s address: ";
getline(cin, address);
}
while (cityStZip.length() == 0)
{
cout << "Enter the " << fname << " " << lname << "'s city, state and zip code: ";
getline(cin, cityStZip);
}
/* The following section is going to be where the user will
input their specificed amounts for each cookie type */
thin_mints = getCookies(cookie1, max_order); // input for Thin Mints
cout << "Thin Mints amount: " << thin_mints << endl;
lemonUps = getCookies(cookie2, max_order); // input for Lemon-Ups
cout << "Lemon-Ups amount: " << lemonUps << endl;
lemonades = getCookies(cookie3, max_order); // input for Lemonades
cout << "Lemonades amount: " << lemonades << endl;
samoas = getCookies(cookie4, max_order); // input for Samoas
cout << "Samoas amount: " << samoas << endl;
tagalongs = getCookies(cookie5, max_order); // input for Tagalongs
cout << "Tagalongs amount: " << tagalongs << endl;
dosidos = getCookies(cookie6, max_order); // input for Do-si-dos
cout << "Do-si-dos amount: " << dosidos << endl;
trefoils = getCookies(cookie7, max_order); // input for Trefoils
cout << "Trefoils amount: " << trefoils << endl;
thanksalot = getCookies(cookie8, max_order); // input for Thanks-A-Lot
cout << "Thanks-A-Lot amount: " << thanksalot << endl;
toffee = getCookies(cookie9, max_order); // input for Toffee-tastic
cout << "Toffee-tastic amount: " << toffee << endl;
caramel = getCookies(cookie10, max_order); // input for Caramel Chocolate Chip
cout << "Caramel Chocolate Chip amount: " << caramel << endl;
if (outFile.is_open())
{
outFile << "================================" << endl;
outFile << "=== Girl Scout Cookie Invoice ===" << endl;
outFile << "================================\n" << endl;
string dateStr;
time_t result = time(NULL);
dateStr = ctime(&result);
outFile << dateStr << endl;
outFile << fname << " " << lname << endl;
outFile << address << endl;
outFile << cityStZip << endl;
outFile << endl;
outFile << "Order Number: " << orderNumber << endl;
outFile << endl;
outFile << "Dear " << fname << " " << lname << ":" << endl;
outFile << endl;
outFile << "Your Girl Scout Cookie order has arrived." << endl;
outFile << "Your order consists of the following:" << endl;
outFile << "-------------------------------------------------" << endl;
outFile << "|" << setw(14) << "Cookie" << setw(11) << "|" << setw(9) << "Quantity" << setw(2) << "|" << setw(7) << "Cost" << setw(5) << "|" << endl;
outFile << "-------------------------------------------------" << endl;
outFile << "|" << setw(11) << "Thin Mints" << setw(14) << "|" << setw(9) << thin_mints << setw(2) << "|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << thin_mints * cPrice << setw(2) << "|" << endl;
outFile << "|" << setw(9) << "Lemon-up" << setw(16) << "|" << setw(9) << lemonUps << setw(2) << "|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << lemonUps * cPrice << setw(2) << "|" << endl;
outFile << "|" << setw(10) << "Lemonades" << setw(15) << "|" << setw(9) << lemonades << setw(2) << "|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << lemonades * cPrice << setw(2) << "|" << endl;
outFile << "|" << setw(7) << "Samoas" << setw(18) << "|" << setw(9) << samoas << setw(2) << "|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << samoas * cPrice << setw(2) << "|" << endl;
outFile << "|" << setw(10) << "Tagalongs" << setw(15) << "|" << setw(9) << tagalongs << setw(2) << "|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << tagalongs * cPrice << setw(2) << "|" << endl;
outFile << "|" << setw(10) << "Do-si-dog" << setw(15) << "|" << setw(9) << dosidos << setw(2) << "|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << dosidos * cPrice << setw(2) << "|" << endl;
outFile << "|" << setw(9) << "Trefoils" << setw(16) << "|" << setw(9) << trefoils << setw(2) <<"|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << trefoils * cPrice << setw(2) << "|" << endl;
outFile << "|" << setw(13) << "Thanks-A-Lot" << setw(12) << "|" << setw(9) << thanksalot << setw(2) << "|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << thanksalot * cPrice << setw(2) << "|" << endl;
outFile << "|" << setw(14) << "Toffee-Tastic" << setw(11) << "|" << setw(9) << toffee << setw(2) << "|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << toffee * cPrice << setw(2) << "|" << endl;
outFile << "|" << setw(23) << "Caramel Chocolate Chip" << setw(2) << "|" << setw(9) << caramel << setw(2) << "|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << caramel * cPrice << setw(2) << "|" << endl;
outFile << "-------------------------------------------------" << endl;
outFile << "|" << setw(33) << "Total Due:" << setw(3) << "|" << setw(2) << "$" << setw(8) << fixed << setprecision(2) << cPrice * (thin_mints + lemonUps + lemonades + samoas + tagalongs + dosidos + trefoils + thanksalot + toffee + caramel) << setw(2) << "|" << endl;
outFile << "-------------------------------------------------" << endl;
}
}
}
int getCookies(string cookietype, int max_order)
{
int quantity = -1;
int min_order = 0;
while ((quantity < min_order) || (quantity > max_order))
{
cout << cookietype;
cin >> quantity;
cin.clear();
}
return quantity;
}
You need to enter the value of a variable before you use it, not afterwards. For example
for (;;) // loop until we break
{
// get the number of oreos
cout << "Enter the number of Oreos (0-10): ";
cin >> numOreos;
// check the number of oreos is OK
if (numOreos >= 0 && numOreos <= 10)
break; // quit the loop if it is
// ignore any extraneous input and try again
cin.ignore(100, '\n');
cin.clear();
}
See that the test on the number of Oreos happens after the user has input a value, not before.
In your code with the while loop you were checking the value of numOreos when it had not yet been given a value. C++ programs are sequences of instructions and the order things happen is important. They are not declarations of intent where you just say 'I want the variable to be within these values' and leave it up the computer to figure it out.

How to append new data to a text file in C++ without outputting the title again?

I have a problem in outputting my code to a text file. I just wanted to print a title at the beginning of a .txt file, but it happened to end up printing along with new lines of data. Basically, I am appending new data to the text file using ios::app. How can I achieve not printing my title in the text file all over again after appending other data?
Text File Output
Here is my code btw...
#include <iostream>
#include <fstream>
#include <string>
void QuaranDiary();
struct quarantine3 //structure for QuaranDiary
{
string QuaranDiaryMonth;
string QuaranDiaryDay;
string QuaranDiaryYear;
string QuaranDiaryHour;
string QuaranDiaryMinute;
string QuaranDiaryUpdate;
};
quarantine3 diary[500];
//QuaranDiary
void QuaranDiary()
{
int i = 0, update = 0;
char QuaranDiaryMore;
do
{
cout << "=====================================================================================" << endl;
cout << " COVID-19 QUARANDIARY " << endl;
cout << "=====================================================================================" << endl << endl;
cout << "DATE (MM/DD/YYYY)" << endl << endl;
cout << "Month : ";
cin >> diary[i].QuaranDiaryMonth;
cout << "Day : ";
cin >> diary[i].QuaranDiaryDay;
cout << "Year : ";
cin >> diary[i].QuaranDiaryYear;
cout << endl;
cout << "[" << diary[i].QuaranDiaryMonth << "/" << diary[i].QuaranDiaryDay << "/" << diary[i].QuaranDiaryYear << "]" << endl << endl;
cout << "TIME (23:59)"<<endl<<endl;
cout << "Hour : ";
cin >> diary[i].QuaranDiaryHour;
cout << "Minute : ";
cin >> diary[i].QuaranDiaryMinute;
cout << endl;
cout << "[" << diary[i].QuaranDiaryHour << ":" << diary[i].QuaranDiaryMinute << "]" << endl << endl;
cout << "Health Update: ";
cin.ignore();
getline(cin, diary[i].QuaranDiaryUpdate);
update++;
cout << "\n\nAdd More to QuaranDiary? [Y/N]: ";
cin >> QuaranDiaryMore;
QuaranDiaryMore = toupper(QuaranDiaryMore);
while (toupper(QuaranDiaryMore) != 'Y' && toupper(QuaranDiaryMore) != 'N')
{
cout << "\nWrong Input. Try Again!\n" << endl;
cin.clear();
cin.ignore();
cout << "Add More to QuaranDiary? [Y/N]: ";
cin >> QuaranDiaryMore;
}
cin.clear();
cin.ignore();
system("CLS");
//fstream for QuaranDiary
ofstream QuaranDiary;
QuaranDiary.open("QuaranDiary.txt", ios::app);
QuaranDiary << "=====================================================================================" << endl;
QuaranDiary << " COVID-19 QUARANDIARY " << endl;
QuaranDiary << "=====================================================================================" << endl;;
QuaranDiary << "\nDate: " << diary[i].QuaranDiaryMonth << "/" << diary[i].QuaranDiaryDay << "/" << diary[i].QuaranDiaryYear;
QuaranDiary << "\tTime: " << diary[i].QuaranDiaryHour << ":" << diary[i].QuaranDiaryMinute << endl << endl;
QuaranDiary << "[Health Update]\n\n" << diary[i].QuaranDiaryUpdate << endl;
QuaranDiary << "=====================================================================================" << endl;
if (QuaranDiary.is_open())
{
cout << "\nCheck QuaranDiary.txt for your written health updates!" << endl;
}
else
{
cout << "\n\nUnable to Open File!" << endl;
}
QuaranDiary.close();
} while (toupper(QuaranDiaryMore == 'Y'));
}

C++ not getting all lines from .txt file when tokenising

I am trying to read in my text file that contains book list.
However, when I output the file that I read in, I found there is some left out.
I'm wondering if the problem is happening when I try to tokenise the file.
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <string>
#include <conio.h>
#include <cctype>
using namespace std;
typedef struct
{
int shelf;
int level;
} LOCATION_TYPE;
typedef struct
{
char isbn[14];
char author[40];
char title[40];
char publisher[40];
int year;
char genre[20];
char price[10];
char quantity[3];
LOCATION_TYPE location;
} BOOK_TYPE;
void menu();
void list(BOOK_TYPE book[], int total_book);
void search(BOOK_TYPE students[], int total_student);
int main(void)
{
BOOK_TYPE book[100];
ifstream input("booklist.txt"); // read input from a text file.
if (!input) // check error.
{
cout << "Error opening file.\n";
exit(100); // testing if the text file is connected
}
else
{
char delim[] = ",";
char temp[100];
int index = -1, choice;
input.getline(temp, 100, '\n');
while(input)
{
char* token = strtok(temp, delim);
strcpy(book[++index].isbn, token);
strcpy(book[index].author, strtok(NULL, delim));
strcpy(book[index].title, strtok(NULL, delim));
strcpy(book[index].publisher, strtok(NULL, delim));
book[index].year = atoi(strtok(NULL, delim));
strcpy(book[index].price, strtok(NULL, delim));
strcpy(book[index].quantity, strtok(NULL, delim));
book[index].location.shelf = atoi(strtok(NULL, delim));
book[index].location.level = atoi(strtok(NULL, delim));
strcpy(book[index].genre, strtok(NULL, delim));
// clear unwanted whitespace
if (input.peek() == '\n')
input.ignore(256, '\n');
// read next number
input.getline(temp, 100, '\n');
//token = strtok(book[++index], delim);
}
input.close();
system("cls");
menu();
cin >> choice;
while (choice != 0)
{
if (choice == 1)
{
list(book, index);
}
else if (choice == 2)
{
search(book, index);
}
else
{
system("cls");
cout << "Invalid input. Please key in number 0-4.\n";
system("pause");
}
system("cls");
menu();
cin >> choice;
}
}
return 0;
}
void menu()
{
cout << "UNDERGROUND BOOKS" << endl;
cout << "1. List all books record" << endl;
cout << "2. Search books" << endl;
cout << "3. Add books" << endl;
cout << "4. Delete books" << endl;
cout << "0. Exit" << endl;
cout << "What would you like to do?" << endl;
}
void list(BOOK_TYPE book[], int total_book)
{
system("cls");
for (int i = 0; i < total_book; i++)
{
cout << left << setw(15) << "ISBN" << setw(20) << "Author" << setw(35) << "Title"
<< setw(25) << "Publisher" << setw(7) << "Year" << setw(15) << "Genre"
<< setw(4) << "Qty" << setw(6) << "Price" << endl;
cout << "________________________________________________________________________________________________________________________________\n" << endl;
cout << left << setw(15) << book[i].isbn
<< setw(20) << book[i].author
<< setw(35) << book[i].title
<< setw(25) << book[i].publisher
<< setw(7) << book[i].year
<< setw(15) << book[i].genre
<< setw(4) << book[i].quantity
<< setw(6) << book[i].price << endl << endl
<< "(Located at shelf " << book[i].location.shelf << " level " << book[i].location.level << ")" << endl << endl;
cout << "________________________________________________________________________________________________________________________________" << endl;
}
system("pause");
}
void search(BOOK_TYPE book[], int total_book)
{
char keyword[55];
char* substring;
char tempKeyword[20];
system("cls");
// Prompt and get keyword to search student
cout << "Enter ISBN, book title or author name to search: ";
while (getchar() != '\n');
cin.getline(keyword, 55);
for (int i = 0; i < (int)strlen(keyword); i++)
{
keyword[i] = toupper(keyword[i]); //capitalize all of the character
}
for (int i = 0; i < total_book; i++)
{
substring = strstr(book[i].isbn, keyword);
if (substring)
{
cout << left << setw(15) << "ISBN" << setw(20) << "Author" << setw(35) << "Title"
<< setw(25) << "Publisher" << setw(7) << "Year" << setw(15) << "Genre"
<< setw(4) << "Qty" << setw(6) << "Price" << endl;
cout << "________________________________________________________________________________________________________________________________\n" << endl;
cout << left << setw(15) << book[i].isbn
<< setw(20) << book[i].author
<< setw(35) << book[i].title
<< setw(25) << book[i].publisher
<< setw(7) << book[i].year
<< setw(15) << book[i].genre
<< setw(4) << book[i].quantity
<< setw(6) << book[i].price << endl << endl
<< "(Located at shelf " << book[i].location.shelf << " level " << book[i].location.level << ")" << endl << endl;
cout << "________________________________________________________________________________________________________________________________" << endl;
}
else if (strstr(book[i].author, keyword) != 0)
{
cout << left << setw(15) << "ISBN" << setw(20) << "Author" << setw(35) << "Title"
<< setw(25) << "Publisher" << setw(7) << "Year" << setw(15) << "Genre"
<< setw(4) << "Qty" << setw(6) << "Price" << endl;
cout << "________________________________________________________________________________________________________________________________\n" << endl;
cout << left << setw(15) << book[i].isbn
<< setw(20) << book[i].author
<< setw(35) << book[i].title
<< setw(25) << book[i].publisher
<< setw(7) << book[i].year
<< setw(15) << book[i].genre
<< setw(4) << book[i].quantity
<< setw(6) << book[i].price << endl << endl
<< "(Located at shelf " << book[i].location.shelf << " level " << book[i].location.level << ")" << endl << endl;
cout << "________________________________________________________________________________________________________________________________" << endl;
}
}
system("pause");
}
Here is my book list I'm having in text file:
9781785785719,Yasha Levine,Surveillance Valley,Icon Books,2019,57.95,3,1,1,Political Science
9780241976630,John Maeda,How to Speak Machine,Portfolio UK,2019,89.95,2,1,1,Non-Fiction
9781119055808,Andre De Vries,R For Dummies,John Wiley,2015,107.77,4,1,2,Design
9780062018205,Dan Ariely,Predictably Irrational,Harper Collins,2010,39.90,2,1,1,Legal opinion
9780008327613,John Waish,The Globalist,Harper Collins,2019,109.90,2,1,1,Non-Fiction
9780525538349,John Doerr,Measure What Matters,Penguin LCC,2018,86.95,2,1,2,Management
9780807092156,Viktor Frankl,Man's Search for Meaning,Random House,2019,49.90,3,1,3,Biography
9780809875214,John Wick,The Assasinate of a Gang,Tree Production,2014,39.00,4,2,2,Fiction
9788373191723,J.R.R Tolkien,The Lord of the Rings,Allen & Unwin,1954,120.45,6,3,1,Fantasy Adventure
9783791535661,Lewis Carroll,Alice's Adventure in Wonderland,Macmillan,1865,100.25,5,3,2,Fantasy Fiction
9781517322977,Mikhail Bulgakov,The Master and Margarita,Penguin Books,1967,125.00,7,3,3,Romance Novel
9780676516197,Vladmir Nabokov,Lolita,Olympia Press,1955,98.25,3,3,1,Tragicomedy
9781095627242,Anna Sewell,Black Beauty,The Jarrold Group,1877,60.25,2,3,2,Fiction Novel
9788497592581,Umberto Eco,The Name of the Rose,Bompiani,1980,45.65,7,1,3,Historical Fiction
9780545790352,J.K.Rowling,Harry Potter and the Sorcerer's Stone,Arthur A. Levine,2015,44.87,1,3,1
I manage to only output until John Wick (8th line from text file) when user prompt "1" at the menu to show book list.

How would I go about outputting the output from ALL of the above code?

Basically I want an exact copy of the code that appears in the console window to also be outputted to a txt file..
#include <conio.h>
#include <iostream>
#include <dos.h>
#include <stdlib.h>
#include <windows.h>
#include <stdio.h>
#include <fstream>
using namespace std;
//Initialising gotoxy Comand
void gotoxy(int col, int row)
{
COORD coord;
coord.X = col;
coord.Y = row;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
int main()
{
char name1[20], name2[20], name3[30], name4[20];
int funcNum = 0;
int n1Nv, n1Mv, n1SEv, n1SWv;
int n2Nv, n2Mv, n2SEv, n2SWv;
int n3Nv, n3Mv, n3SEv, n3SWv;
int n4Nv, n4Mv, n4SEv, n4SWv;
int n1Total, n2Total, n3Total, n4Total, perTotal;
double n1Per, n1PerTotal;
double n2Per, n2PerTotal;
double n3Per, n3PerTotal;
double n4Per, n4PerTotal;
double maxVote;
//Introduction
cout << "================================================================================";
cout << " Ballot Results" << endl;
cout << " Version 2.1" << endl;
cout << " Created by Team b0nkaz" << endl;
cout << "================================================================================" << endl;
//Candidate Identification
cout << "Enter the candidates running for president" << endl << endl;
//cin.getline (workaround,30); //**
cout << "Candidate One: ";
cin.getline (name1,20);
cout << "Candidate Two: ";
cin.getline (name2,20);
cout << "Candidate Three: ";
cin.getline (name3,20);
cout << "Candidate Four: ";
cin.getline (name4,20);
cout << " " << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
cout << "Input vote numbers from each region pressing enter after each input:" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
//Input Table
//Regions
gotoxy(22,19);
cout << "North" << endl;
gotoxy(31,19);
cout << "Midlands" << endl;
gotoxy(43,19);
cout << "South East" << endl;
gotoxy(57,19);
cout << "South West" << endl;
gotoxy(69,19);
cout << "| Total" << endl;
cout << "_____________________________________________________________________|__________" << endl;
gotoxy(69,21);
cout << "|";
gotoxy(69,22);
cout << "|";
gotoxy(69,23);
cout << "|";
gotoxy(69,24);
cout << "|";
gotoxy(69,25);
cout << "|";
gotoxy(69,25);
cout << "|";
gotoxy(69,26);
cout << "|";
gotoxy(69,27);
cout << "|";
gotoxy(69,28);
cout << "|";
gotoxy(69,29);
cout << "|";
//Candidates
gotoxy(0,22);
cout << name1;
gotoxy(0,24);
cout << name2;
gotoxy(0,26);
cout << name3;
gotoxy(0,28);
cout << name4;
//Equals
cout << endl;
cout << "_____________________________________________________________________|__________" << endl;
//Vote Input
//North
gotoxy(22,22);
cin >> n1Nv;
gotoxy(22,24);
cin >> n2Nv;
gotoxy(22,26);
cin >> n3Nv;
gotoxy(22,28);
cin >> n4Nv;
//Midlands
gotoxy(31,22);
cin >> n1Mv;
gotoxy(31,24);
cin >> n2Mv;
gotoxy(31,26);
cin >> n3Mv;
gotoxy(31,28);
cin >> n4Mv;
//South East
gotoxy(43,22);
cin >> n1SEv;
gotoxy(43,24);
cin >> n2SEv;
gotoxy(43,26);
cin >> n3SEv;
gotoxy(43,28);
cin >> n4SEv;
//South West
gotoxy(57,22);
cin >> n1SWv;
gotoxy(57,24);
cin >> n2SWv;
gotoxy(57,26);
cin >> n3SWv;
gotoxy(57,28);
cin >> n4SWv;
//Total Votes
//Name1
gotoxy(72,22);
n1Total = n1Nv + n1Mv + n1SEv + n1SWv;
cout << n1Total;
//Name2
gotoxy(72,24);
n2Total = n2Nv + n2Mv + n2SEv + n2SWv;
cout << n2Total;
//Name3
gotoxy(72,26);
n3Total = n3Nv + n3Mv + n3SEv + n3SWv;
cout << n3Total;
//Name4
gotoxy(72,28);
n4Total = n4Nv + n4Mv + n4SEv + n4SWv;
cout << n4Total << endl << endl << endl;
//Percentage Calculation
perTotal = n1Total + n2Total + n3Total + n4Total;
//Candidate One
n1Per = n1Total*100;
n1PerTotal = n1Per/perTotal;
//Candidate Two
n2Per = n2Total*100;
n2PerTotal = n2Per/perTotal;
//Candidate Three
n3Per = n3Total*100;
n3PerTotal = n3Per/perTotal;
//Candidate Four
n4Per = n4Total*100;
n4PerTotal = n4Per/perTotal;
cout << "Please wait for calculation..." << endl << endl;
//Spinning Loading Line
//std::cout << '-' << std::flush;
//for(;;)
//{
//Sleep(100);
//std::cout << "\b\\" << std::flush;
//Sleep(100);
//std::cout << "\b|" << std::flush;
//Sleep(100);
//std::cout << "\b/" << std::flush;
//Sleep(100);
//std::cout << "\b-" << std::flush;
//}
//Sleeping Program
Sleep(1500); //1.5 secs
//Total Output
cout << "Candidate percentage:" << endl << endl;
//Converting To One Decimal Place
cout << fixed;
std::cout.precision(1);
//Vote Percentages
cout << name1 << " = " << n1PerTotal << "%" << endl;
cout << name2 << " = " << n2PerTotal << "%" << endl;
cout << name3 << " = " << n3PerTotal << "%" << endl;
cout << name4 << " = " << n4PerTotal << "%" << endl << endl;;
//Calculating Winnner
maxVote=n1PerTotal;
if (n2PerTotal>maxVote)
maxVote=n2PerTotal;
if (n3PerTotal>maxVote)
maxVote=n3PerTotal;
if (n4PerTotal>maxVote)
maxVote=n4PerTotal;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
//Sleeping Program
Sleep(1500); //1.5 secs
if(maxVote==n1PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name1 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n1PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
else if(maxVote==n2PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name2 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n2PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
else if(maxVote==n3PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name3 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n3PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
else if(maxVote==n4PerTotal)
{
cout << " ***********************************************************************" << endl;
cout << " " << name4 << " " << endl;
cout << " is the new president of The British Society of IT Professionals " << endl;
cout << " with " << n4PerTotal << "% of the vote " << endl;
cout << " ***********************************************************************" << endl << endl;;
//Separator
cout << "--------------------------------------------------------------------------------" << endl;
}
cout << "Press any key to exit..." << endl;
getch();
//system("pause");
}
I am using MS Visual Studio 2010 and any help would be great! Please note I am still very new to C++.
EDIT I would like to be able to see the output in CMD as well as have a separate txt file with the same output code. Everything that is displayed in the CMD window also copied into the txt file.
use an ofstream operator as such.
For some reason I can't seem to find the comment button or I would be involved in the discussion above... but I've edited my code below to reflect what seem to be some concerns of yours.
#include<fstream>
using namespace std;
int main()
{
ofstream fout;
fout.open("data.txt"); //Will create a new file if one is not already in existence
//You can put a static filename here or have them enter a string
//If you use a custom string your input will be "fout.open(STRING.c_str());
fout<<"Used exactly like cout from this point on";
fout.close(); //When you are done using it to close the file
}
I chose to name my ofstream operator fout because (while this is not always good to do) this way you can quickly change all of your cout's to fout's, or replicate them.
If the user enters a value and you want to spit it back out as well, you can use the ofstream operator after every cin.
You can find more information about ofstream here...
Hope this helped!
You can do this from outside of the application using tee. tee takes the output of a program and splits it into two streams (e.g. one to stdout and one to a file). Unfortunately, Windows doesn't come with a tee command but there are many implementations available.
If you want this to happen from within your program you can do the equivalent of tee using a custom ofstream. This article explains how.

Help implementing a "store buying" program

My professor instructed us to make a Starbucks like menu where the user can continue to input orders until they are finished. I got the menu display down along with the loop, but I can't get it to add up the orders that were inputted and display a total.
#include <iostream>
using namespace std;
int main()
{
int choice = 1;
cout << endl << "Welcome to Hunterbucks!";
while (choice > 0)
{
cout << endl << "Input -1 when you're finished ordering!";
cout << endl << endl << "Coffee" << " " << "($)";
cout << endl << "1. Regular" << " " << "1.50";
cout << endl << "2. Decaf" << " " << "1.23";
cout << endl << "3. Americano" << " " << "2.25";
cout << endl << "4. Espresso" << " " << "2.25";
cout << endl << "5. Latte" << " " << "2.50";
cout << endl << "6. Cappuccino" << " " << "2.75";
cout << endl << "7. Frappuccino" << " " << "2.75";
cout << endl << "8. Macchiato" << " " << "2.50";
cout << endl << endl << "Snacks" << " " << "($)";
cout << endl << "9. Muffin" << " " << "1.00";
cout << endl << "10. Blueberry Muffin" << " " << "1.25";
cout << endl << "11. Raspberry Muffin" << " " << "1.25";
cout << endl << "12. Scone" << " " << "0.75";
cout << endl << "13. Blueberry Scone" << " " << "1.00";
cout << endl << "14. Croissant" << " " << "0.75";
cout << endl << endl << "What would you like to order? ";
cin >> choice;
if (choice <= 0)
cout << endl << "Thank you for your order.";
else
cout << endl << "What else would you like to order?";
}
cout << endl << "Thank you for choosing Hunterbucks! Come again soon.";
return 0;
}
Any info that can help me? I'm just a beginner and have been trying this for a few hours.
In pseudo-code you want something like this:
float total = 0.0;
while (choice > 0)
{
....
cin >> choice;
if (choice <= 0)
cout << endl << "Thank you for your order.";
else
{
total += costs[choice];
cout << endl << "What else would you like to order?";
}
}
You'll need to define an array names costs that contains the cost of each item. You'll also want to tackle validation of the user input so that you don't erroneously attempt to read outside the range of the costs array.
You're probably looking at something like this:
#include <iostream>
using namespace std;
int main()
{
int choice = 1;
float sum = 0.0;
float arr[] = {
0.00, 1.50, 1.23, 2.25, 2.25, 2.50, 2.75, 2.75, 2.50,
1.00, 1.25, 1.25, 0.75, 1.00, 0.75
};
cout << endl << "Welcome to Hunterbucks!";
while (choice > 0)
{
cout << endl << "Input -1 when you're finished ordering!";
cout << endl << endl << "Coffee" << " " << "($)";
cout << endl << "1. Regular" << " " << "1.50";
cout << endl << "2. Decaf" << " " << "1.23";
cout << endl << "3. Americano" << " " << "2.25";
cout << endl << "4. Espresso" << " " << "2.25";
cout << endl << "5. Latte" << " " << "2.50";
cout << endl << "6. Cappuccino" << " " << "2.75";
cout << endl << "7. Frappuccino" << " " << "2.75";
cout << endl << "8. Macchiato" << " " << "2.50";
cout << endl << endl << "Snacks" << " " << "($)";
cout << endl << "9. Muffin" << " " << "1.00";
cout << endl << "10. Blueberry Muffin" << " " << "1.25";
cout << endl << "11. Raspberry Muffin" << " " << "1.25";
cout << endl << "12. Scone" << " " << "0.75";
cout << endl << "13. Blueberry Scone" << " " << "1.00";
cout << endl << "14. Croissant" << " " << "0.75";
cout << endl << endl << "What would you like to order? ";
cin >> choice;
if (choice <= 0){
cout << endl << "Thank you for your order.";
} else {
cout << endl << "What else would you like to order?";
sum += arr[choice];
}
}
cout << "Total: " << sum << endl;
cout << endl << "Thank you for choosing Hunterbucks! Come again soon.";
return 0;
}
Do note the following:
1) Your menu choices being with '1' thus there is a need to offset your arr at index '0' with the '0.00' value there.
2) The cost added up follows that of your indexed array, thus you would probably want to format your output according to your array, so that next time, all you need to do is to update your array.
Hope it helped. Cheers!
The way you have your code set up warrants a switch statement, like the following:
double total = 0;
switch (choice)
{
case 1:
total += 1.50; // Regular.
break;
case 2:
total += 1.23; // Decaf.
break;
// Etc.
}
cout << endl << "Your total is " << total;
That being said, the easiest way to do this would be to have an array of prices:
double prices[] = {1.50, 1.23, 2.25};
// ...
total += prices[choice - 1]; // No switch statement needed.