Why the result doesn't write on the text file? - c++

I have created csis.txt file but when I look up, it is empty. Could anyone teach me why the file is created without results? Here are my codes:
//ZipCode.cpp
#include <iostream>
#include "ZipCode.h"
#include <fstream>
#include <string>
#include <math.h>
#include <sstream>
using namespace std;
extern ofstream csis;
ZipCode::ZipCode(int _zipcode) {
zipcode = _zipcode;
}
ZipCode::ZipCode(const char *barcode) {
int value;
zipcode = 0;
for (int i = 0; i<5; i++) //repeat x5 positions
{
value = 0;
for (int j = 0;j<5;j++) //repeat x5 letters
{
if (barcode[i * 5 + j] == '1') //if '1' is letter
{
value += base[j]; //add position(5)
}
}
if (value >10)
{
value = 0;
}
zipcode = zipcode * 10 + value;
}
}
string ZipCode::getBarCode()
{
char barcode[26] = "";
int zip = zipcode;
int value;
for (int i = 0;i<5;i++) //repeat x5 positions
{
for (int j = 0;j<4;j++) //repeat x4(last barcode position 0)
{
//10^position * barcode position goes to value
value = (int)(pow(10.0, 4 - i) * base[j]);
if (zip / value)
{
barcode[i * 5 + j] = '1'; //set as '1'
zip = zip % value;//zip is now remainder
}
else
{
barcode[i * 5 + j] = '0'; //set as '0'
}
}
barcode[i * 5 + 4] = '0';
}
return barcode;
}
int ZipCode::getZipCode()
{
return zipcode;
}
//ZipCode.h
#ifndef _ZIPCODE_H
#define _ZIPCODE_H
using namespace std;
class ZipCode {
private:
int zipcode;
int base[5] = { 7,4,2,1,0 }; //barcode positions
public:
ZipCode(int _zipcode); //convert zipcode to barcode
ZipCode(const char *barcode); //convert barcode to zipcode
string getBarCode(); //get barcode
int getZipCode(); //get zipcode
};
#endif
//main.cpp
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include "ZipCode.h"
#include <sstream>
using namespace std;
ofstream csis;
int main()
{
csis.open("csis.txt");
ZipCode zip1(99504);
ZipCode zip2(12345);
ZipCode zip3(67890);
ZipCode zip4("100101010011100001100110001");
ZipCode zip5("110100001011100001100010011");
ZipCode zip6("100011000110101000011100101");
cout << "Digits" << " " << "Bar Code" << endl;
cout << zip1.getZipCode() << setw(35) << zip1.getBarCode() << endl;
cout << zip2.getZipCode() << setw(35) << zip2.getBarCode() << endl;
cout << zip3.getZipCode() << setw(35) << zip3.getBarCode() << endl;
cout << endl;
cout << zip4.getZipCode() << setw(35) << zip4.getBarCode() << endl;
cout << zip5.getZipCode() << setw(35) << zip5.getBarCode() << endl;
cout << zip6.getZipCode() << setw(35) << zip6.getBarCode() << endl;
return 0;
}

You probably want to write the file rather than std::cout.
Just replace :
cout << "Digits" << " " << "Bar Code" << endl;
by
csis << "Digits" << " " << "Bar Code" << endl;`
And repeat that for every line...

Related

Getting average age of students and youngest student's name

I'm having some trouble with getting the average age of all students including getting the youngest student's name outputted. The output is supposed to come from a function call I wrote called ageCalc(...).
main.cpp
#include <iostream>
#include <fstream>
#include <iomanip>
#include "Student1.h"
#include "Student2.h"
#include "ageCalc.h"
using namespace std;
const int SIZE = 100;
int main()
{
ifstream inFile;
inFile.open("C:\\COMSC200\\a2data.input", ios::in|ios::binary);
// Open the input file – if it fails to open, display an error message and terminate
if(!inFile.is_open())
{
cout << "Unable to open file!";
return 1;
}
else
{
cout << "File successfully open!\n\n";
}
// Use a pointer array to manage all the created student variables.
Student1 **ptrArr = new Student1 *[SIZE];
Student1 s;
int total = 0;
// read the first input record
inFile.read(reinterpret_cast<char *> (&s), sizeof(s));
while(!inFile.eof())
{
// dynamically allocate space for new student variable
ptrArr[total] = new Student1;
// populate the student variable from the input
*ptrArr[total] = s;
total++;
// read the next input record
inFile.read(reinterpret_cast<char *> (&s), sizeof(s));
}
Student2 *st = new Student2[SIZE];
for(int i = 0; ptrArr[i]; i++)
{
for(char fn: ptrArr[i]->first_name)
st[i].fn += fn;
st[i].mi = ptrArr[i]->middle_int[0];
for(char ln: ptrArr[i]->last_name)
st[i].ln += ln;
st[i].cc = ptrArr[i]->campus_code;
for(char sID: ptrArr[i]->student_ID)
st[i].sID += sID;
st[i].age = atoi(ptrArr[i]->age);
}
cout << "First Name" << setw(9)
<< "MI" << setw(15)
<< "Last Name" << setw(17)
<< "Campus Code" << setw(16)
<< "Student ID" << setw(15)
<< "Age" << endl;
cout << "===================================================================================" << endl;
for(int j = 0; st[j].age != 0; j++)
{
cout << st[j].fn << setw(8);
cout << st[j].mi << " ";
cout << st[j].ln << setw(2);
cout << st[j].cc << " ";
cout << st[j].sID << setw(16);
cout << st[j].age << " " << endl;
}
Student2 *y;
int avg = ageCalc(&st, y);
cout << "Average student age is: " << avg << " years." << endl;
cout << "Youngest student is: " << arr[i]->fn << " " << arr[i]->mi << " " << arr[i]->ln << endl;
for(int x = 0; ptrArr[x]; x++)
{
delete ptrArr[x];
}
delete [] st;
inFile.close();
return 0;
}
ageCalc.cpp
#include "Student2.h"
using namespace std;
int ageCalc(Student2 *arr[], Student2 *&y)
{
int i = 0, sum = 0, index = 0, avg;
while(arr[i] != nullptr)
{
sum = arr[i]->age + sum;
i++;
if(arr[i]->age < arr[index]->age)
{
index = i;
}
}
y = arr[index];
avg = sum / i;
return avg;
}
Student1.h
#ifndef STUDENT1_H_
#define STUDENT1_H_
#include <iostream>
using namespace std;
struct Student1
{
char first_name[10];
char middle_int[10];
char last_name[20];
char campus_code;
char student_ID[8];
char age[3];
};
#endif
Student2.h
#ifndef STUDENT2_H_
#define STUDENT2_H_
#include <iostream>
#include <string>
using namespace std;
struct Student2
{
string fn;
char mi;
string ln;
char cc;
string sID;
short int age;
};
#endif
ageCalc.h
#ifndef AGECALC_H_
#define AGECALC_H_
#include "Student2.h"
int ageCalc(Student2 *[], Student2 *&);
#endif

cargo transportation system we are not sure how to display the last part of our task

Here is our code for the task we are almost finishing just the last part we are stuck at
"Fastest: 3 trips (1 Van, 3 Mini-lorry, $645) "
we are not sure how to display the values in the bracket we only able to display 3 trips.
Is there a way to also display the values in the bracket stated as well?
we use
int min = *min_element(vTrips.begin(), vTrips.end());
cout << "Fastest: " << min << " trips" << endl;
but this only display the 3 trips.
#include <iostream>
#include <vector>
#include <iterator>
#include <fstream>
#include<algorithm>
using namespace std;
class CTS //cargo transport system
{
int i;
int cargo, lorryprice, vanprice, lorrysize, vansize, allOps;
public:
void set_cargo(int);
void set_lorryprice(int);
void set_vanprice(int);
void set_lorrysize(int);
void set_vansize(int);
};
void CTS::set_cargo(int total_cargo) {
cargo = total_cargo;
}
void CTS::set_lorryprice(int lorryP) {
lorryprice = lorryP;
}
void CTS::set_vanprice(int vanP) {
vanprice = vanP;
}
void CTS::set_lorrysize(int lorryS) {
lorrysize = lorryS;
}
void CTS::set_vansize(int vanS)
{
vansize = vanS;
}
int main()
{
int cargo, lorryprice, vanprice, lorrysize, vansize, options, i, no_lorry, no_van, cost, trips;
ifstream infile;
infile.open("size.txt");
if (infile.is_open()) {
infile >> cargo;
infile >> lorryprice;
infile >> vanprice;
infile >> lorrysize;
infile >> vansize;
}
CTS run;
run.set_cargo(cargo);
run.set_lorryprice(lorryprice);
run.set_vanprice(vanprice);
run.set_lorrysize(lorrysize);
run.set_vansize(vansize);
infile.close();
options = (cargo / lorrysize) + 1;
no_lorry = (cargo / lorrysize);
no_van = (cargo / vansize) + 3;
if (cargo % lorrysize == 0) {
no_van = -3;
}
if (cargo % lorrysize != 0) {
no_van = ((cargo % lorrysize) / 10) - 3;
}
/*it = numbervan.begin();
for (auto ir = numbervan.rbegin(); ir != numbervan.rend(); ++ir) {
cout << *ir << endl;
}*/
vector<int> vCost, vVan, vTrips, vLorry;
vector <int>::iterator it;
for (i = 1; i < options + 1; i++)
{
int numberlorry = no_lorry;
cout << "Option " << i << ":" << endl;
cout << "Number of Mini-Lorries : " << no_lorry-- << endl;
if (no_van >= -3) {
no_van += 3;
}
cout << "Number of Vans : " << no_van << endl;
int numbervan = no_van;
if (numberlorry > numbervan) {
trips = numberlorry;
}
else {
trips = numbervan;
}
cout << "Trips Needed : " << trips << endl;
cost = (numberlorry * lorryprice) + (no_van * vanprice);
cout << "Total Cost : $" << cost << endl;
vCost.push_back(cost);
vLorry.push_back(numberlorry);
vVan.push_back(numbervan);
vTrips.push_back(trips);
}
int counter = vCost.size() - 1;
//std::vector<int>::reverse_iterator ir = vCost.rbegin();
for (i = 1; i < 4; i++) {
//cout << "Lowest #" << i << ": "<<cost<<endl;
cout << "Lowest #" << i << ": $" << vCost[counter] << "(" << vVan[counter] << " Vans, " << vLorry[counter] << " Mini-Lorry, " << vTrips[counter] << " Trips)" << endl;
counter--;
}
int min = *min_element(vTrips.begin(), vTrips.end()); // this line of code we figured out how to
cout << "Fastest: " << min << " trips" << endl; //display the number of trips using algorithm
return 0;
}
Your design is awkward; you create an instance of CTS run; and never use it.
Assuming that you do your calculations right, you need to know at what index you found min. If you store the iterator returned by min_element(), you can get an index by subtracting vTrips.begin() from it. Then the corresponding elements in your vCost, vLorry and vVan vectors will contain the data you want.
However, it would be easier if you define a struct containing your pre-calculated values, and push that into some vector. In that case, all related data is kept together.

Function return nothing with multiple files?

When I run one file, it works perfectly. Then I separate 3 file: header, main, function from that file. It aslo works but return nothing. Here the code:
File Header: printStudent.h
//Header.h
#ifndef PRINTSTUDENT_H_INCLUDED
#define PRINTSTUDENT_H_INCLUDED
void read ();
#endif
File Function: readFileCSV.cpp . It read and print from my .csv file
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string.h>
#include <algorithm>
#define student 1000
using namespace std;
void read (){
ifstream readFileCSV;
readFileCSV.open("studentEn.csv");
if(!readFileCSV.is_open()) {cout << "ERROR: File can't be opened or it doesn't exist" << endl;};
string aMSSV[student];
string aname[student];
string abirthDay[student];
string aaddress[student];
string MSSV;
string name;
string birthDay;
string address;
int countStudent = 0;
while(readFileCSV.good()) {
getline(readFileCSV, MSSV, ',');
getline(readFileCSV, name, ',');
getline(readFileCSV, birthDay, ',');
getline(readFileCSV, address, '\n');
int lengthAddress = address.length();
char charAddress[lengthAddress];
strcpy(charAddress, address.c_str());
char newCharAddress[lengthAddress-2];
for(int i = 0 ; i < lengthAddress-2 ; i++){
newCharAddress[i] = charAddress[i+1];};
string address(newCharAddress, lengthAddress - 2);
aMSSV[countStudent] = MSSV;
aname[countStudent] = name;
abirthDay[countStudent] = birthDay;
aaddress[countStudent] = address;
countStudent ++;
};
countStudent = countStudent - 1;
cout << "..................................................STUDENT..........................................................." << endl;
cout << setw(5) << left << "STT";
cout << setw(25) << left << "MSSV";
cout << setw(25) << left << "Name";
cout << setw(25) << left << "Date of Birth";
cout << left << "Address";
cout << endl;
cout << "...................................................................................................................." << endl;
for(int i = 0 ; i < countStudent ; i++){
cout << setw(5) << left << i + 1;
cout << setw(25) << left << aMSSV[i];
cout << setw(25) << left << aname[i];
cout << setw(25) << left << abirthDay[i];
cout << left << aaddress[i];
cout << endl;
}
readFileCSV.close();
}
File main:
#include <iostream>
#include "printStudent.h"
using namespace std;
int main(){
void read ();
return 0;
}
Help me why it's return nothing and give me a solution how can i make it works? Thanks!
int main(){
void read ();
return 0;
}
It is a function declaration in main a.k.a. forward declaration. Any expression that starts with a type or void is a declaration. It is a local declaration, thus it doesn't conflict with the globally declared function read.
To call the function do it so
int main(){
read ();
return 0;
}

c++ vector of structs inside class

hello all i am working on a school prject called inventory inquisitor. the specifications are as follows:
enter image description here
so far i have created a class in which contains a struct and a vector of this struct.
all im trying to do so far is get the class to display the struct just to know it works but when i compile it and run it nothing happens. here is the code. excuse whatever rookie mistakes i have made i am very new with classes, and vectors. thanks you in advance!
//Inventory Inquisitor.cpp
#include <iostream>
#include <string>
#include <cctype> //for toupper
#include <fstream>
#include <vector>
using namespace std;
class Inventory
{
private:
struct item
{
string Description = " ";
double Quantity = 0;
double Wholesalescost = 0;
double Retailcost = 0;
string Dateadded = " ";
};
vector<item> Inv;
public:
void Display();
};
void Inventory::Display()
{
Inv[0].Description = "english";
Inv[0].Quantity = 1;
Inv[0].Wholesalescost = 100;
Inv[0].Retailcost = 200;
Inv[0].Dateadded = "3/8/2018";
cout << Inv[0].Description << endl;
cout << Inv[0].Quantity << endl;
cout << Inv[0].Wholesalescost << endl;
cout << Inv[0].Retailcost << endl;
cout << Inv[0].Dateadded << endl;
}
int main()
{
Inventory inst1;
inst1.Display();
}
You have to put something into the vector before accessing it:
// Create an item
item i;
i.Description = "english";
i.Quantity = 1;
i.Wholesalescost = 100;
i.Retailcost = 200;
i.Dateadded = 3/8/2018;
// The vector is empty, size() == 0
// Add it to the vector
Inv.push_back(i);
// Now the vector has 1 item, size() == 1
// Now you can print it
cout << Inv.at(0).Description << endl;
cout << Inv.at(0).Quantity << endl;
cout << Inv.at(0).Wholesalescost << endl;
cout << Inv.at(0).Retailcost << endl;
cout << Inv.at(0).Dateadded << endl;
According to your assignment, you will most likely change to function to print an existing item. You will have another function to add items to the vector.
void Inventory::Display(int index)
{
// Print an item already in the vector
if (index >= 0 && index < Inv.size()) {
cout << Inv.at(index).Description << endl;
cout << Inv.at(index).Quantity << endl;
cout << Inv.at(index).Wholesalescost << endl;
cout << Inv.at(index).Retailcost << endl;
cout << Inv.at(index).Dateadded << endl;
}
}

reading double from a binary file (into a class) - decimals do not show

having trouble displaying the decimals after reading the data.
As the title says.. here are some code snippets.
the header for the student obj
class StudentRecordData
{
protected:
double Marks[MAX_COURSES];
unsigned int Age;
unsigned int ID;
unsigned int CourseCount;
char FirstName[LEN_FN];
char LastName[LEN_FN];
Course Courses[MAX_COURSES];
};
student header:
class Student : public StudentRecordData {
public:
double *getMarks();
unsigned int getAge();
unsigned int getID();
unsigned int getCourseCount();
char *getFirstName();
char *getLastName();
Course *getCourses();
double getAverage();
int operator < (Student &);
int operator < (const char &);
};
Student implementation (inherited the above)
#include "Student.h"
#include <iostream>
#include <cstring>
using namespace std;
double *Student::getMarks() {
return Marks;
}
unsigned int Student::getAge() {
return Age;
}
unsigned int Student::getID() {
return ID;
}
unsigned int Student::getCourseCount() {
return CourseCount;
}
char *Student::getFirstName() {
return FirstName;
}
char *Student::getLastName() {
return LastName;
}
Course *Student::getCourses() {
return Courses;
}
int Student::operator<(Student &s) {
int ret = 0;
int LNRet = strcmp(this->getLastName(), s.getLastName());
int FNRet = strcmp(this->getFirstName(), s.getFirstName());
if (LNRet < 0) {
ret = 1;
} else if (LNRet == 0) {
if (FNRet < 0) {
ret = 1;
}
}
return ret;
}
int Student::operator<(const char &s) {
cout << "in char *!" << endl;
int ret = 0;
return ret;
}
double Student::getAverage() {
double total = 0.00;
for (int i = 0; i < (getCourseCount()); i++) {
total = total + getMarks()[i];
}
return total / getCourseCount();
}
the main
#include "Course.h"
#include "Student.h"
#include "Node.h"
#include "LinkedList.h"
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main(void) {
char input[] = "OOP344.dat";
char output[] = "OUTPUT.txt";
Student student;
LinkedList list;
Node *node;
// read in file
ifstream ifile(input, ios::binary);
while (!ifile.eof()) {
ifile.read(reinterpret_cast<char *>(&student), sizeof(Student));
node = new Node(student);
list.addNode(node);
}
ifile.close();
list.sort();
// write to file
ofstream ofile(output);
if (ofile.is_open()) {
for (node = list.getFirstNode(); node; node = list.getNextNode(node)) {
cout << setw(10) << "Last Name" << setw(12) << "First Name" << setw(5) << "Age" << setw(12) << "Student ID" <<
setw(15) << "Course" << setw(7) << "Mark" << endl;
cout << setw(10) << "=========" << setw(12) << "==========" << setw(5) << "===" << setw(12) << "==========" <<
setw(15) << "======" << setw(7) << "=====" << endl;
cout << setw(10) << node->getValue().getLastName()
<< setw(12) << node->getValue().getFirstName()
<< setw(5) << node->getValue().getAge()
<< setw(12) << node->getValue().getID()
<< setw(22) << node->getValue().getAverage()
<< endl;
int sem, sem_prev;
for (int i = 0; i < node->getValue().getCourseCount(); i++) {
sem = (int)node->getValue().getCourses()[i].Semester;
sem_prev = (int)node->getValue().getCourses()[i-1].Semester;
if (!(sem == sem_prev)) {
cout << setw(45) << "Sem " << (int)node->getValue().getCourses()[i].Semester << ":"
<< setw(7) << node->getValue().getCourses()[i].Name
<< setw(7) << setprecision(4) << node->getValue().getMarks()[i] << endl;
} else {
cout << setw(54) << node->getValue().getCourses()[i].Name
<< setw(7) << setprecision(4) << node->getValue().getMarks()[i] << endl;
}
}
cout << endl;
}
}
ofile.close();
return (0);
}
output:
Last Name First Name Age Student ID Course Mark
========= ========== === ========== ====== =====
Sakedad Roya 25 486503 74.31
Sem 1: APC100 69
EAC150 92
ICA002 76
IOS110 87
IPC144 99
Sem 2: ULI101 62
DBS201 66
IBC233 94
INT222 58
OOP244 67
Sem 3: DBS301 61
INT322 89
SYS366 52
BAC344 80
OOP344 63
Sem 4: DCN455 74
the problem is in this line near the bottom. it won't display any decimal points. any help is greatly appreciated.
setprecision(4) << node->getValue().getMarks()[i]
i can supply any other files which may be helpful. i'm just hoping my mistakes are somewhere in the main.
You've given us a lot of code to wade through for a simple
formatting issue, but I don't see where you tell the output
stream how you want the floating point values formatted. The
default formatting is defined so that it will result in
something readable for all possible values, but in practice,
it's never what you want for any particular set of values
(except maybe in log files or for serialization purposes). In
your case (and in a lot of smaller programs), you could probably
get by with just setting the floating point format to fixed:
ofile.setf( std::ios_base::fixed, std::ios_base::floatfield );
More generally, the best practice would be to define a
manipulator for the different semantic values you need: e.g.:
std::ostream&
mark( std::ostream& dest )
{
dest.setf( std::ios_base::fixed, std::ios_base::floatfield );
dest.precision( 2 );
return dest;
}
You can then simply write:
ofile << ... << mark << node->getValue().getMarks()[i] << ...
Note, however, that both the format option and the precision are
sticky; they will remain set until changed. In any significant
code, it is a good practice to reset them to what they were
before.