Constructor Operator << Device and Test Dynamic Array - file

#include iostream
#include cmath
#include fstream
#include cstdlib
#include string
using namespace std;
class Device {//Input and store Device Description and Serial Numbers
protected:
static string serial_number;
static string device_description;
public:
Device() {
serial_number = ("6DCMQ32");
device_description = ("TheDell");
}
Device(string s, string d) {
serial_number = s;
device_description = d;
}
};
string Device::device_description;
string Device::serial_number;
class Test {//Input and store Test Description, recent day, and month;
Calculate the next day
protected:
static string Test_Description;
static int recent_month, recent_day, recent_year, new_month;
static int nmonth, next_month, next_day, next_year, max_day;
public:
Test() {
Test_Description = ("Virtual");
}
static void getMonth() {//Calculates the next/new month
next_month = recent_month + nmonth;
new_month = next_month % 12;
if (next_month >= 12) {
cout << "The next Date: " << new_month << " / ";
}
else {
cout << "The next Date: " << next_month << " / ";
}
}
static void getDay() { //Calculates day of next month
if (new_month == 4 || new_month == 6 || new_month == 9 || new_month == 11) {
max_day = 30;
}
else if (new_month == 2) {
max_day = 29;
}
else {
max_day = 31;
}
if (recent_day > max_day) {
cout << max_day << " / ";
}
else {
cout << recent_day << " / ";
}
}
static void getYear() {// Calculate the year of next month
next_year = recent_year + next_month;
if (next_year >= 12) {
cout << recent_year + (next_month / 12) << endl;
}
else {
cout << next_year << endl;
}
}
static void getDate() {// Collects the output of each element of next date
Test::getMonth(), Test::getDay(), Test::getYear();
}
};
string Test::Test_Description;
int Test::recent_month;
int Test::recent_day;
int Test::recent_year;
int Test::new_month;
int Test::nmonth;
int Test::next_month;
int Test::next_day;
int Test::next_year;
int Test::max_day;
class Lab : public Device, public Test {
protected:
static int n;
public:
friend istream & operator>>(istream & in, Lab & lab) {// Inputs
cout << "Enter Device Desciption and Serial Number: ";
getline(in, device_description);
getline(in, serial_number);
cout << "Enter Test Desciption: ";
getline(in, Test_Description);
cout << "Enter the Number of months: ";
in >> nmonth;
cout << "Enter the Most Recent Date(mm/dd/yyyy): ";
in >> recent_month >> recent_day >> recent_year;
return in;
}
friend ostream & operator<<(ostream & out, Lab & lab) {//Outputs
everything in Device Class
out << Lab::device_description << endl;
out << Lab::serial_number << endl;
out << Lab::Test_Description << endl;
getDate();
return out;
}
static void getN() {
cout << "Enter the number of devices: ";
cin >> n;
}
static void getWrite() {
Lab *obj = new Lab[n];
if (obj == 0) {
cout << "Memory Error";
exit(1);
}
for (int i = 0; i<n; i++) {
cin >> obj[i];
cout << endl;
}
ofstream myfile("Device.txt");
myfile.write((char *)obj, n * sizeof(Lab));
delete[] obj;
}
static void getRead() {
ifstream file2("Device.txt");
Lab *obj2 = new Lab[n];
if (obj2 == 0) {
cout << "Memory Error";
exit(1);
}
file2.read((char *)obj2, n * sizeof(Lab));
for (int i = 0; i < n; i++) {
cout << obj2[i];
cout << endl;
}
delete[] obj2;
}
/*void getSearch(){
}*/
};
int Lab::n;
void main() {
Lab L;
L.getN();
L.getWrite();
L.getRead();
system("pause");
}
The Output I get is TheDell 6DCMQ32, Virtual when I entered my inputs. The date is correct the only problem is the Device Description, Serial Number, and Test Device.
Problem with Operator << in File i/o reading where it outputs the values in the Constructor
Purpose: is to enter the number of months for the next test date of device with input of serial number,
Device Description, Test Description, recent date, and the number of months of two tests. At the end the
program must be searched by having the user to input the serial number and the next date, if these two are
valid everything in the device is listed out.

Short of writing your application, I will do my best to give you some direction.
#include <iostream> // Note the '<' and '>' this is to specify is a language provided include
// More includes with the same issue...
using namespace std; // this is general considered bad=practice see https://stackoverflow.com/a/1452738/8480874 for details
//Input and store Device Description and Serial Numbers
class Device
{ // Notice the white space makes it easier to read...
protected:
//static string serial_number; // declaring this static means _EVERY_ device will have the same serial number
//static string device_description; // same as above
string serialNumber;
string deviceDesc;
public:
Device() : serialNumber("6DCMQ32"), deviceDesc("TheDell")
{
//serial_number = ("6DCMQ32"); // Not the best place for initialization
//device_description = ("TheDell"); // Not the best place for initialization
}
//Device(string s, string d) // you never actually use this
//{
// serial_number = s;
// device_description = d;
//}
};
//string Device::device_description; // This is a sign that you variable will be shared between everyone - not required if you remove the static
//string Device::serial_number; // This is a sign that you variable will be shared between everyone - not required if you remove the static
// This suffers from the same probles as the `class device` above
class Test
{
// Lots of stuff was here just trying to short the answer....
// Mostly has the same culprits mentions for the device
// This is one of the fucntions which gets called when you are trying to "save" the info to a file
static void getMonth(/* ostream & out */) // you need this as a paramater
{
next_month = recent_month + nmonth;
new_month = next_month % 12;
if (next_month >= 12)
{
// This function has no idea is needs to redirect the out put to a file...
// its only outputting to the standard console
cout << "The next Date: " << new_month << " / ";
}
else
{
//cout << "The next Date: " << next_month << " / ";
// using the new parameter in comments
// you can now save to your file
out << /*"The next Date: " <<*/ next_month << " / "; // no I comment out your extra message since you file reading does not look for that
}
}
};
// Again we have the same general misuse of C++ ( please keep learning! hopefully I am point you in the right direction )
class Lab : public Device, public Test
{
protected:
static int n;
public:
friend istream & operator>>(istream & in, Lab & lab)
{
// Inputs
cout << "Enter Device Desciption and Serial Number: ";
getline(in, device_description);
getline(in, serial_number);
cout << "Enter Test Desciption: ";
getline(in, Test_Description);
cout << "Enter the Number of months: ";
in >> nmonth;
cout << "Enter the Most Recent Date(mm/dd/yyyy): ";
in >> recent_month >> recent_day >> recent_year;
return in;
}
friend ostream & operator<<(ostream & out, Lab & lab) {//Outputs
everything in Device Class
out << Lab::device_description << endl;
out << Lab::serial_number << endl;
out << Lab::Test_Description << endl;
// Here you should pass the output pipe
getDate(/* out */);
return out;
}
static void getN() {
cout << "Enter the number of devices: ";
cin >> n;
}
static void getWrite()
{
// there's no real need to be using a pointer or memory allocation
//Lab *obj = new Lab[n];
// you can simply use
Lab obj[n];
//if (obj == 0)
//{
// cout << "Memory Error";
// exit(1);
//}
for (int i = 0; i < n; i++)
{
cin >> obj[i];
cout << endl;
}
ofstream myfile("Device.txt");
//myfile.write((char *)obj, n * sizeof(Lab)); // I've never tried writting an object's memory as a char* to file
// usually I like to generate a human readable output
std::string objBuffer = obj.getSaveBuffer(); // you will need to implement this `getSaveBuffer()` functions
myfile << objBuffer; // This can save lots of different value types for you! see http://www.cplusplus.com/reference/ostream/ostream/operator%3C%3C/
//delete[] obj; // since there is no more new; we dont need a delete!
}
// The logic of what you read suffers the same general issues as the write.
// Also what/how you read is very far from the save so I can't venture into any solutions
// I'm hoping this will kick start you to figuring it out on your own =)
static void getRead() {
ifstream file2("Device.txt");
Lab *obj2 = new Lab[n];
if (obj2 == 0) {
cout << "Memory Error";
exit(1);
}
file2.read((char *)obj2, n * sizeof(Lab));
for (int i = 0; i < n; i++) {
cout << obj2[i];
cout << endl;
}
delete[] obj2;
}
/*void getSearch(){
}*/
};
int Lab::n;
// A program that runs should always return a numeric result indicating success or failure
//void main() {
int main()
{
Lab L; // Since everything in all your classes is static this didnt really add anything
// you done need an object if the object contains nothing
L.getN();
L.getWrite();
L.getRead();
system("pause"); // this is also bad practice, see https://stackoverflow.com/a/1107717/8480874
// I personally like `getchar()` because it's easy and quick
}

Related

How to make Account user generator c++ (problem: making array of objects and dynamically expanding it)

I'm 15 and I moved to Sweden. I don't have time to study c++, because I need to learn the language, but later (few months probably), I'll continue with 300 page book (it's 500, but in 3 years I learned (through YouTube mostly) about 200 pages of that book). I'm not willing to learn right now about vector, so if you give me answer with vector, if you could explain to me how it works, or give me link where it "simply" explains vector.
Anyway, being all said and done, here's my problem:
I'm building in c++ program that on the start, it has 1 object(NAobj) where it will store your name and age, and then you can select option to continue to create another account, and so on. When you first run that program it makes Aobj array object and expands it every time when you want create new account. But I just can't get it to work.
I found how I can expand array of objects, but, as I said, it's not realy working...
How to expand an array dynamically in C++? {like in vector }
Here's my code:
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int AccountFinder(string findName, string accountNames);
class Account
{
public:
Account()
{
}
~Account()
{
}
string name = "-ERROR NAME-";
int age = 18;
private:
};
Account NAobj;
int Asize = 1;
string AName;
string Iname;
int ASelector;
int main() {
Account *Aobj = new Account[Asize];
while (Iname.empty()) {
cout << "Name: #";
getline(cin, Iname);
if (Iname.empty())
{
cout << '\a' << endl;
MessageBox(NULL, "No name found\nPlease enter name", "Error 01", MB_ICONERROR);
system("cls");
}
else if (Iname == " ") {
cout << '\a' << endl;
MessageBox(NULL, "Non suported name", "Error 02", MB_ICONERROR);
system("cls");
Iname.clear();
}
else {
string a;
cout << "Crete account? y\\n #";
getline(cin, a);
if (a == "y") {
AName += Iname;
////generatin account
NAobj.name = Iname;
Account *TAobj = new Account[Asize];
if (Asize == 1) {
copy(Aobj, Aobj + Asize - 1, TAobj);
delete[] Aobj;
Aobj = TAobj;
copy(Aobj, Aobj + Asize - 1, &NAobj);
}
else {
copy(Aobj, Aobj + Asize - 1, TAobj);
copy(&NAobj, &NAobj, (TAobj + Asize - 1));
delete[] Aobj;
Aobj = TAobj;
}
////
AName += " ";
cout << "Want to continue? y\\n #";
getline(cin, a);
if (a == "y") {
system("cls");
Iname.clear();
}
else {
AName.resize(AName.size() - 1);
}
Asize++;
}
else {
cout << "Want to continue? y\\n #";
getline(cin, a);
if (a == "y") {
system("cls");
Iname.clear();
}
else {
AName.resize(AName.size() - 1);
}
}
}
}
Iname.clear();
cout << ">" << AName << "<" << endl;
cout << AName << endl;
string name;
cin >> name;
int ANumber = AccountFinder(name, AName);
if(ANumber != -1)
cout << ANumber << endl;
else
cout << "no account name: >" << name << "< found" << endl;*/
cout << endl;
system("pause");
}
int AccountFinder(string findName, string accountNames) {
string compareName;
int Account = 0;
bool space = TRUE;
int startPos = 0;
int a = 0;
while (1) {
while (1) {
if (accountNames.at(a) == ' ') {
break;
}
else
a++;
if (a == accountNames.size() - 1)
return -1;
}
compareName.resize(a - startPos);
for (int b = startPos; b < a; b++) {
compareName.at(b - startPos) = accountNames.at(b);
}
if (findName == compareName) {
return Account;
}
a++;
startPos = a;
if (Account > 0) {
1;
}
Account++;
}
}
Asize - Account Size (indicate size of array)
Aobj - Account Object (array of account objects)
NAobj - New Account Object ("temporary" storage for account name, probably won't use that later...)
Program Output
p.s.
Sorry for my bad english and i know my program is a mess, but i'm lazy to tidy it up.
The simplest solution to your problem is using a vector to store references to objects of the class. I recommend going to the "trouble" of learning how to use vectors. They are not as difficult to understand as you might fear, and are definitely one of the simplest dynamic data structures.
This might help: https://www.geeksforgeeks.org/vector-in-cpp-stl/

On the output in the for loop it is displaying zero and not accepting the input I cannot figure out what i am doing wrong here

#include <iostream>
#include <exception>
using namespace std;
class Inventory{
friend istream& operator>>(istream&, Inventory);
friend ostream& operator<<(ostream&, Inventory);
private:
int stock;
int quant;
int price;
public:
Inventory(int=0,int=0,double=0);
};
Inventory::Inventory(int s, int q, double p){
stock=s;
quant=q;
price=p;
}
istream& operator>>(istream& in, Inventory){
int s;
int q;
double p;
cout << "Enter stock number: ";
in >> s;
cout << "Enter quantity: ";
in >> q;
cout << "Enter price: ";
in >>p;
Inventory inv(s,q,p);
return in;
}
ostream& operator<<(ostream& out, Inventory inv){
out << "The stock number is: " << inv.stock << endl << "The quantity is: " <<
inv.quant << endl << "The price is: " << inv.price << endl;
return out;
}
int main()
{
Inventory inv[5]={};
for(int i = 0; i <5; i++){
cin >> inv[i];
}
cout<<"------------------------" << endl;
for(int i=0;i<5;i++){
cout<<inv[i];
cout<<"------------------------" << endl;
}
return 0;
}
I can not figure out why when I use the overloaded << operator in the for loop it is displaying zero's, am I not storing the price, quantity and price to the object array correctly? I have tried not using a contructor and using one it did not make a difference, any ideas why the integers and double are not storing to the array?
Your were close! See my // change here comment markers (there are several) in the code below.
The 0's had nothing to do with the << overload, but rather the >> overload.
The deal is that you can use the 'in' istream to input directly to the class variables (without trying to call some other function, or a need for extra variables) in the >> overload, but you need to pass an Inventory reference to do so.
I was surprised that there was no error trying to set primitives to 0 in the constructor parameters?? (I'm likely very 'rusty' on newer C++ handling, been over 15+ years for me), but anyway:
#include <iostream>
#include <exception>
using namespace std;
class Inventory{
friend istream& operator>>(istream&, Inventory&); // change here (Inventory reference)
friend ostream& operator<<(ostream&, Inventory);
private:
int stock;
int quant;
double price; // change here
public:
Inventory(int,int,double); // change here
};
Inventory::Inventory(int s = 0, int q = 0, double p = 0){ // change here
stock=s;
quant=q;
price=p;
}
istream& operator>>(istream& in, Inventory& inv){ // change here (inventory reference)
// change here (removed variables)
cout << "Enter stock number: ";
in >> inv.stock; // change here
cout << "Enter quantity: ";
in >> inv.quant; // change here
cout << "Enter price: ";
in >> inv.price; // change here
// change here (removed function call)
return in;
}
ostream& operator<<(ostream& out, Inventory inv){
out << "The stock number is: " << inv.stock << endl << "The quantity is: " <<
inv.quant << endl << "The price is: " << inv.price << endl;
return out;
}
int main()
{
const int ITEMS = 5; // change here (constant to replace hard-coded value)
Inventory inv[ITEMS]={}; // change here (use the constant)
for(int i = 0; i <ITEMS; i++){ // change here (use the constant)
cin >> inv[i];
}
cout<<"------------------------" << endl;
for(int i=0;i<ITEMS;i++){ // change here (use the constant)
cout<<inv[i];
cout<<"------------------------" << endl;
}
return 0;
}
Give that a run and see how it goes:
Here's my example output when I changed the constant (my change inside the main function) to 2 for a basic test run:
Enter stock number: 123
Enter quantity: 4
Enter price: 2.1
Enter stock number: 467
Enter quantity: 1
Enter price: 1.2
------------------------
The stock number is: 123
The quantity is: 4
The price is: 2.1
------------------------
The stock number is: 467
The quantity is: 1
The price is: 1.2
------------------------

C++ How to Increment Int Variable From String Array Element

I'm wondering if there is a way to increment an int variable when a specific string array element is called? I'm working on a project for fun and have run into a roadblock. The goal of my project is to have a program that determines what genres of electronic music the user likes. The program will present two DJ's and ask the user which one they prefer or allow them to select neither. Each DJ will have up to three genres that they mainly specialize in, and I have created int variables for each (with all being set to 0). Once a user selects a DJ, I want points to be assigned to each genre variable in which the DJ is associated with. I'm unsure of how to set up this rule as everything I have attempted so far has failed (two example attempts are commented out in the code). Eventually my plan is to develop logic to have the DJ's randomly selected, however I need to have the genre tally allocation set up first. Is there any way this can be done? Any help would be greatly appreciated. Cheers!
###include "stdafx.h"
###include < iostream>
###include < iomanip>
###include < string>
###include < array>
###using namespace std;
int main()
{
cout << "Hello! This program is designed to figure out what Electronic Music you like based on artists presented and the answers you choose...\n" << endl;
cout << "When you are ready to begin press \"Enter\"..." << endl;
getchar();
int bigRoom = 0;
int deepHouse = 0;
int drumBass = 0;
int dubstep = 0;
int electroHouse = 0;
int futureHouse = 0;
int hardDance = 0;
int house = 0;
int progressiveHouse = 0;
int techno = 0;
int trance = 0;
int trap = 0;
string textArray[5]{ "DeadMau5", "Armin Van Buuren", "Avicii", "Ferry Corsten", "Kaskade"};
string answer;
cout << "Select the DJ you prefer by number. Otherwise select 3 if you don't know them. " << endl; //Haven't coded option 3 yet.
cout << "1 - " << textArray[1] << endl;
cout << "2 - " << textArray[2] << endl;
cin >> answer;
/*
if (textArray[1]) {
++trance;
}
for (textArray[1]) {
++trance;
}
*/
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
}
//cout << trance << endl;
}
You can increment each tally once the user has selected a DJ:
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
++trance;
// ++ ohter genres you want to increment
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
++trance;
// ++ ohter genres you want to increment
}

How do you convert a string holding a date from DD-MM-YYYY to MM-DD-YYYY

I have been working on this for about a week and for some reason I just can't get past it. I am getting an out of range error when I am searching the elements of the array, and attempt to move the characters I need to a need array.
void showFileDateCleansed(string first[], string last[], string birthday[])
{
string tempHoldDD[10];
string tempHoldMM[10];
/*
The stuff below is working so Ijust commented it out until I figure out the isssue I am having with the dates
for (int i = 0; i < 6; i++)
{
first[i].at(0) = toupper(first[i].at(0));
last[i].at(0) = toupper(last[i].at(0));
}
for (int i = 0; i < 10; i++)
{
cout << first[i] << " ";
cout << last[i] << "\n";
}*/
int d = 0; //Im using this to keep track of whether I have passed the delimiter in the text file "-"
bool done = false;
for (int i = 0; i < 10; i++)
{
done = false;
int c = 0;//this is used for the character within the element of the array, it increments at the bottom so that it moves to the next character.
while (done != true)
{
// <TK> Check for invalid character
if (c == 0)
{
std::cout << "Invalid character at index: " << i << std::endl;
}
if (birthday[i].at(c) == '-')
{
d += 1;
done = true;
}
else
{
switch (d)
{
case 0:
{
// Try catch to prevent the out of range exception from crashing.
//try
//{
// Debug
std::cout << "C: " << c << std::endl;
// create a temporary variable for the value.
char temp = birthday[i].at(c);
tempHoldDD[i].at(c) = temp;
//}
/*catch (std::out_of_range const& exc)
{
std::cout << exc.what() << '\n';
}*/
//cout << tempHoldMM[c] << "\n";
}
case 1:
{
// Try catch to prevent the out of range exception from crashing.
try
{
// Debug
std::cout << "C: " << c << std::endl;
// create a temporary variable for the value.
char temp = tempHoldMM[i].at(c);
birthday[i].at(c) = temp;
}
catch (std::out_of_range const& exc)
{
std::cout << exc.what() << '\n';
}
//cout << tempHoldMM[c] << "\n";
c += 1;
break;
}
}
}
}
}
Your case 1 in your switch statement doesn't have a break statement, so it will fall through to case 2, where c is incremented. Could that make c get out of range too fast?

Program wont change array value

(Win32 console app) Ok so i know its a bit to look at, but ive added as many helpful comments that i could think of, im sort of new to coding so if this is a quick fix i apologize for taking your time, ive searched high and low and cant figure this out. So, it prompts the user for a name, that works, then for a race, that works, but under the display function, it fails to show the updated stats (updated by which race you choose). although sometimes it will work with the hp/maxHP but not att nor def. im not sure if its something to do with the scope or what, ive tried all i know :/ thanks for your time and help :)
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int stats[6] = {1, 10, 10, 1, 0, 0};//life(0), maxHp(1), hp(2), att(3), def(4), gold(5)
void shop();//goes to the shop
void fight();//goes to fighting area
void sleep();//refills hp
void welcome();//establishes name
void display();//hud
void whereTo();//travel selection
void doRace();//establishes name
void human();//race#1
void orc();//race#2
void dwarf();//race#3
string name;//variable for name
//Main
int main()
{
welcome();
doRace();
while(stats[0]==1)
{
whereTo();
cout << stats[1];
system("PAUSE");
}
cout << "If you are reading this, you have DIED!\n";
system("PAUSE");
return 0;
}
void shop()
{
display();
cout << "To-be shoping area.\n";
system("PAUSE");
}
void fight()
{
display();
cout << "To-be fighting area.\n";
system("PAUSE");
}
void sleep()
{
display();
cout << "You rest completely..." << endl;
stats[2] = stats[1];
system("PAUSE");
}
void whereTo()
{
display();
cout << "Where would you like to go?\n\n Shop(1)\n Fight(2)\n Sleep(3)\n";
int place;
cin >> place;
system("CLS");
if(place==1)
{
shop();
}
else if(place==2)
{
fight();
}
else if(place==3)
{
sleep();
}
else
{
cout << "Please enter 1, 2, or 3.";
system("PAUSE");
system("CLS");
whereTo();
}
}
void display()//Header to everything
{
system("CLS");
cout << name << " HP: " << stats[2] << "/" << stats[1] << " Att: " << stats[3] << " Def: " << stats[5] << " Gold:" << stats[5] << endl << endl;
}
void welcome()//runs once, establishes name in beginning
{
cout << "Welcome to my first RPG Program\n\n";
system("PAUSE");
system("CLS");
cout << "Enter your character's name\n\n";
cin >> name;
system("CLS");
}
void doRace()//choosing a race at the start
{
cout << "What Race would you like to be?\n\n\n 1)Human (More Attack and Defense)\n\n 2)Orc (More Hp and Attack)\n\n 3)Dwarf (More HP and Defense)\n\n";
int race;
cin >> race;
if(race==1)
{
human();
cout << "You chose Human!" << endl;
system("PAUSE");
}
else if(race==2)
{
orc();
cout << "You chose Orc!" << endl;
system("PAUSE");
}
else if(race==3)
{
dwarf();
cout << "You chose Dwarf!" << endl;
system("PAUSE");
}
else
{
cout << "Please enter 1, 2, or 3.";
system("pause");
system("CLS");
doRace();
}
}
void dwarf()//sets the initial stats of the character based off of race selection
{
stats[1] = stats[1] + 3;//maxHp
stats[2] = stats[2] + 3;//hp
stats[4] = stats[4] + 2;//def
}
void human()//sets the initial stats of the character based off of race selection
{
stats[3] = stats[3] + 2;//att
stats[4] = stats[4] + 2;//def
}
void orc()//sets the initial stats of the character based off of race selection
{
stats[1] = stats[1] + 3;//maxHp
stats[2] = stats[2] + 3;//hp
stats[3] = stats[3] + 2;//att
}
You are using the wrong index for def. It should be 4
Def: " << stats[5].

Resources