The output of the code show gibberish values for all the variables of the Student struct. When the display function is ran.
I've include the relevant code in each of the add and display function for the binary file.
For the second function, does the seekg pointer automatically move to read the the next record each time the for loop runs?
//Student struct
struct Student
{
char name [30];
float labTest;
float assignments;
float exam;
};
//Writing function
afile.open(fileName,ios::out|ios::binary);
Student S;
strcpy(S.name,"test");
S.labTest = rand()%100+1;
S.assignments = rand()%100+1;
S.exam = rand()%100+1;
afile.write(reinterpret_cast<char*>(&S),sizeof(S));
afile.close();
//Reading function
afile.open(fileName,ios::in|ios::binary);
afile.seekg(0,ios::end);
int nobyte = afile.tellg();
int recno = nobyte / sizeof(Student);
Student S;
//Loop and read every record
for(int i = 0;i<recno;i++)
{
afile.read(reinterpret_cast<char*>(&S),sizeof(S));
cout << "Name of Student: " << S.name << endl
<< "Lab mark: " << S.labTest << endl
<< "Assignment mark: " << S.assignments << endl
<< "Exam mark: " << S.exam << endl << endl;
}
afile.close();
There are a lot of problems with your code:
Calling your write function will permanently overwrite the last written data set. You have to add: ios::append, so that new data will be written behind the last data you wrote before.
After you move with afile.seekg(0,ios::end); to get with tellg the file size, you have to go back to the start of the file before reading with afile.seekg(0,ios::beg)
It looks that you use a char array to store a string. This is not c++ style! And it is dangerous how you use it. If you use strcpy, you can copy a string which is longer than the space you reserved for it. So you should prefer std::string for that. But you can't simply write a struct which constains std::string as binary! To get checked copy you can use strncpy, but that is still not c++ ;)
For the second function, does the seekg pointer automatically move to read the the next record each time the for loop runs?
Yes, the file position moves which each successful read and write.
A general remark writing binary data by simply dumping memory content:
That is not a good idea, because you can only read that data back, if you use the same machine type and the same compiler options. That means: A machine with different endianness will read data totally corrupted. Also a different integer type ( 32 bit vs 64 bit ) will break that code!
So you should invest some time how to serialize data in a portable way. There are a lot of libraries around which can be used to read/write also complex data types like std::string or container types.
A hint using SO:
Please provide code which everybody can simply cut and paste and compiled. I did not know what your Student struct is. So I take a lot of assumptions! Is your struct really using char[]? We don't know!
#include <iostream>
#include <fstream>
#include <cstring>
const char* fileName="x.bin";
struct Student
{
char name[100]; // not c++ style!
int labTest;
int assignments;
int exam;
};
// Writing function
void Write()
{
std::ofstream afile;
afile.open(fileName,std::ios::out|std::ios::binary|std::ios::app);
Student S;
strcpy(S.name,"test"); // should not be done this way!
S.labTest = rand()%100+1;
S.assignments = rand()%100+1;
S.exam = rand()%100+1;
afile.write(reinterpret_cast<char*>(&S),sizeof(S));
afile.close();
}
void Read()
{
//Reading function
std::ifstream afile;
afile.open(fileName,std::ios::in|std::ios::binary);
afile.seekg(0,std::ios::end);
int nobyte = afile.tellg();
int recno = nobyte / sizeof(Student);
afile.seekg(0, std::ios::beg);
Student S;
//Loop and read every record
for(int i = 0;i<recno;i++)
{
afile.read(reinterpret_cast<char*>(&S),sizeof(S));
std::cout << "Name of Student: " << S.name << std::endl
<< "Lab mark: " << S.labTest << std::endl
<< "Assignment mark: " << S.assignments << std::endl
<< "Exam mark: " << S.exam << std::endl << std::endl;
}
afile.close();
}
int main()
{
for ( int ii= 0; ii<10; ii++) Write();
Read();
}
EDIT. Apparently, I was a bit too late in responding. Klaus has compiled a better, more comprehensive response dwelling into other problems regarding C-style char [], std::string and the endianness of the platform.
You should append to the file opened for every record. In your code you don't have this, at all. Please write the code in a way we can copy and paste, and test. As a working example, you should write some code that can be compiled and run as below:
#include <algorithm>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
// Student struct
struct Student {
char name[30];
float labTest;
float assignments;
float exam;
};
// Serializer
void serialize_student(const Student &s, const std::string &filename) {
// Append to the file, do not overwrite it
std::ofstream outfile(filename, std::ios::binary | std::ios::app);
if (outfile)
outfile.write(reinterpret_cast<const char *>(&s), sizeof(Student));
}
// Deserializer
std::vector<Student> deserialize_students(const std::string &filename) {
std::ifstream infile(filename, std::ios::binary);
std::vector<Student> students;
Student s;
while (infile.read(reinterpret_cast<char *>(&s), sizeof(Student)))
students.push_back(std::move(s));
return std::move(students);
}
int main(int argc, char *argv[]) {
// Generate records
std::vector<Student> mystudents;
std::generate_n(std::back_inserter(mystudents), 10, []() {
Student s;
std::strcpy(s.name, "test");
s.labTest = rand() % 100 + 1;
s.assignments = rand() % 100 + 1;
s.exam = rand() % 100 + 1;
return s;
});
// Print and write the records
for (const auto &student : mystudents) {
std::cout << student.name << ": [" << student.labTest << ','
<< student.assignments << ',' << student.exam << "].\n";
serialize_student(student, "students.bin");
}
// Read and print the records
auto records = deserialize_students("students.bin");
std::cout << "===\n";
for (const auto &student : records)
std::cout << student.name << ": [" << student.labTest << ','
<< student.assignments << ',' << student.exam << "].\n";
return 0;
}
Related
What I try to do is to write all output inside a function into a file. Maybe I need a way to assign all output (not only arrays) in test_func to some kind of variable so that I can return it, but I can't figure out.
#include <iostream>
#include <fstream>
#include <functional>
using namespace std;
void test_func()
{
int a[] = {20,42,41,40};
int b[] = {2,4,2,1};
cout << "Below is the result: "<< endl;
for (int i=0; i<4; i++){
cout << "***********************" << endl;
cout << a[i] << " : " << b[i] <<endl;
cout << "-----------------------" << endl;
}
}
void write_to_file(function<void()>test_func)
{
ofstream ofile;
ofile.open("abc.txt");
ofile << test_func(); // This is not allowed
ofile.close();
}
int main()
{
write_to_file(test_func);
return 0;
}
I need to get all output from test_func instead of only the array a and b, because I have multiple functions in different formats, which are all needed to write into the file using same function write_to_file.
Is there any logical way to do this? (or alternative to function?)
Here is some code that will work the way you want. You have to replace std::couts current rdbuf() with the one of the file streams, and reset it afterwards:
void write_to_file(function<void()>test_func) {
ofstream ofile;
ofile.open("abc.txt");
std::streambuf* org = cout.rdbuf(); // Remember std::cout's old state
cout.rdbuf(ofile.rdbuf()); // Bind it to the output file stream
test_func(); // Simply call the anonymous function
cout.rdbuf(org); // Reset std::cout's old state
ofile.close();
}
Here you can see it running as you intended: Demo
To overcome the problem with the varying function signatures, you can use a delegating lambda function:
void test_func2(double a, int b) {
cout << a << " * " << b << " = " << (a * b) << endl;
}
int main() {
// Create a lambda function that calls test_func2 with the appropriate parameters
auto test_func_wrapper = []() {
test_func2(0.356,6);
};
write_to_file(test_func_wrapper); // <<<<< Pass the lambda here
// You can also forward the parameters by capturing them in the lambda definition
double a = 0.564;
int b = 4;
auto test_func_wrapper2 = [a,b]() {
test_func2(a,b);
};
write_to_file(test_func_wrapper2);
return 0;
}
Demo
You can even do this with a little helper class, which generalizes the case for any std::ostream types:
class capture {
public:
capture(std::ostream& out_, std::ostream& captured_) : out(out_), captured(captured_), org_outbuf(captured_.rdbuf()) {
captured.rdbuf(out.rdbuf());
}
~capture() {
captured.rdbuf(org_outbuf);
}
private:
std::ostream& out;
std::ostream& captured;
std::streambuf* org_outbuf;
};
void write_to_file(function<void()>test_func)
{
ofstream ofile;
ofile.open("abc.txt");
{
capture c(ofile,cout); // Will cover the current scope block
test_func();
}
ofile.close();
}
Demo
So regarding your comment:
Sure, but I will require something to store those cout, or maybe there's another completely different way instead of using test_func() for the process?
We have everything at hand now to do this
#include <iostream>
#include <fstream>
#include <functional>
#include <string>
#include <sstream>
using namespace std;
void test_func1(const std::string& saySomething) {
cout << saySomething << endl;
}
void test_func2(double a, int b) {
cout << "a * b = " << (a * b) << endl;
}
class capture {
public:
capture(std::ostream& out_, std::ostream& captured_) : out(out_), captured(captured_), org_outbuf(captured_.rdbuf()) {
captured.rdbuf(out.rdbuf());
}
~capture() {
captured.rdbuf(org_outbuf);
}
private:
std::ostream& out;
std::ostream& captured;
std::streambuf* org_outbuf;
};
int main() {
std::string hello = "Hello World";
auto test_func1_wrapper = [hello]() {
test_func1(hello);
};
double a = 0.356;
int b = 6;
auto test_func2_wrapper = [a,b]() {
test_func2(a,6);
};
std::stringstream test_func1_out;
std::stringstream test_func2_out;
std::string captured_func_out;
{ capture c(test_func1_out,cout);
test_func1_wrapper();
}
{ capture c(test_func2_out,cout);
test_func2_wrapper();
}
captured_func_out = test_func1_out.str();
cout << "test_func1 wrote to cout:" << endl;
cout << captured_func_out << endl;
captured_func_out = test_func2_out.str();
cout << "test_func2 wrote to cout:" << endl;
cout << captured_func_out << endl;
}
And the Demo of course.
The line ofile << test_func(); means that returned value of called test_func(); is directed to that stream. It doesn't do anything to actions done within function called. You may pass stream to the function though.
void test_func(ostream& outs)
{
outs << "Below is the result: "<< endl;
}
and call it with cout or ofile - any ostream as argument.
void write_to_file(function<void(ostream&)>test_func)
{
ofstream ofile;
ofile.open("abc.txt");
test_func(ofile); // This is not allowed
ofile.close();
}
But if the behaviour of function as stream manipulator is something what you want, you have to design a proper operator.
ostream& operator<< (ostream& o, void(*func)(ostream&) )
{
func(o);
return o;
}
Then you can write something like
cout << test_func << " That's all, folks\n";
Note, that test_func isn't called here, its id used as expression results in function's address being passed to operator<<.
Real stream manipulators (e.g. https://en.cppreference.com/w/cpp/io/manip/setw ) implemented not as functions , but as templates of functional objects, the argument of setw in line:
is >> std::setw(6) >> arr;
is actually argument of a constructor
What I try to do is to write all output inside a function into a file.
I often use a std::stringstream to act as a temporary repository for text, i.e. the ss holds and bundles all output into a 'buffer' (a text string) for delay'd output to the file.
For your test_func, you might add a ss reference parameter :
void test_func(std::stringsteam& ss)
{
int a[] = {20,42,41,40};
int b[] = {2,4,2,1};
cout << "Below is the result: "<< endl;
for (int i=0; i<4; i++){
ss << "***********************" << endl;
ss << a[i] << " : " << b[i] <<endl;
ss << "-----------------------" << endl;
}
}
A std::stringstream is essentially a ram-based ofile (with none of the hard disk overhead).
So you can run many test_func's, lump all the output together into one ss, and empty the ss content to the one file.
Or, you might invoke 1 test_func, output / append that ss contents to your ofile, then clear the ss for re-use.
You also might invoke 1 test func, output that ss contents to a unique ofile, then clear the ss and do the next test func, etc.
Note: a) std::stringstream uses one std::string as a working buffer, and b) std::string keeps its data in dynamic memory. I seldom worry about how big the ss gets. But, if you are worried, and have an estimate, you can easily use reserve to set the string size. Knowing this size will allow you to plan to control very big output files.
Next, consider keeping stringstream out of the test_func's, and instead keep it in the outer data gathering function:
void write_to_file(function<void()>test_func)
{
std::stringstream ss; // temporary container
test_func(ss); // add contributions
test_func2(ss); // add contributions
test_func3(ss); // add contributions
// ...
test_funcN(ss); // add contributions
// when all testing is complete, output concatenated result to single file
ofstream ofile;
ofile.open("abc.txt");
ofile << ss.str();
ofile.close();
}
int main()
{
write_to_file(test_func);
return 0;
}
Note: to empty a ss, I use 2 steps:
void ssClr(stringstream& ss) { ss.str(string()); ss.clear(); }
// clear data clear flags
Note: I encapsulate my coding efforts into one or more c++ classes. In my code, the ss objects are declared as a data attribute of my class, and thus accessible to all function attributes of that class, including each test_funci (i.e. no need to pass the ss)
I am a new programmer working in C++, I am trying to make a program that will import information from a file to an output file and then I'm going to do a search algorithm on the data. I am trying to use a structure of data and import that into an array and then call it in the main program.
For some reason I can't, for the life of me, get my function call to work; I keep getting an undeclared identifier error on inputFile in my function call in the main program. I realize I'm probably doing something fundamentally wrong, so I would really appreciate any help that can be given.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
const int MAX_LOG_SIZE = 7584;
const string LOGFILE ="crimes.dat";
const string OUTPUT_FILE ="crimesorted.log";
// Structure of strings based on info from crimes.dat
struct CrimeInfo
{
string Crimedescr;
string Date;
string Time;
string Address;
string Grid;
string Latitude;
string Longitude;
};
CrimeInfo crimeList [MAX_LOG_SIZE];
void openInputFile(ifstream& inputFile, string inputFilename)
// here we open the input file crimes.dat
{
inputFile.open(inputFilename.c_str());
while (inputFile.fail())
{
cout << "Failed to open input file: " << inputFilename << ".\n";
exit(1);
}
};
void getLogEntry(ifstream &LOGFILE, CrimeInfo &entry)
{
getline(LOGFILE, entry.Date);
getline(LOGFILE, entry.Time);
getline(LOGFILE, entry.Address);
getline(LOGFILE, entry.Grid);
getline(LOGFILE, entry.Crimedescr);
getline(LOGFILE, entry.Latitude);
getline(LOGFILE, entry.Longitude);
}
/* opens an output file */
void openOutputFile(ofstream& outputFile, string outputFilename)
{
outputFile.open(outputFilename.c_str());
if (outputFile.fail())
{
cout << "Failed to open output file: " << outputFilename << ".\n";
exit(2);
}
}
void outputLogFile(string outputFilename, CrimeInfo arr[], int size)
{
// open output files
ofstream outputLogFile;
openOutputFile(outputLogFile, outputFilename);
// output the crime file
outputLogFile << "\nCrime log sort ^^:\n\n";
for (int i = 0; i < size; i++)
{
outputLogFile << arr[i].Date << " ";
outputLogFile << arr[i].Address << " (";
outputLogFile << arr[i].Longitude << " ";
outputLogFile << arr[i].Latitude << " ";
outputLogFile << arr[i].Time << " ";
outputLogFile << arr[i].Grid << " ";
outputLogFile << arr[i].Crimedescr << "";
outputLogFile << endl;
}
outputLogFile.close();
}
int main()
{
outputLogFile(OUTPUT_FILE, crimeList, MAX_LOG_SIZE);
for (int i =0; i < MAX_LOG_SIZE; i++)
getLogEntry(inputFile, crimeList[i].Date);
}
There are a lot of problems with your code. To help you out, I went through your code and left a lot of my own comments to tell you some suggestions I had; to make it easy, I deleted your comments so there's no confusion on what was yours and what I put there.
Here are some things I noticed in your code:
using namespace std is generally considered a very bad practice. Instead, just specify the namespace (e.g. std::string instead of just string).
You declared LOGFILE as a string at the top of your program, but then tried to use it as an ifstream& in the function getLogEntry.
Your main method is out of order. I'm assuming you want to load some data into the program from a file and then output that data to another file. The way you have it in your main method is, first, you output information you don't have yet and, second, import information but don't do anything with it.
You have a LOT of functions. As a general rule of thumb, don't make a whole function for opening a file, then a separate one for using it, then a separate one for closing it. There are a lot of big reasons why not to do this. The biggest reasons are that your program becomes very difficult to follow, and no one else will be able to use your code. In real-world applications, your code is only 20% for the computer and 80% for other programmers.
There are various formatting errors and such.
So, here is your original code with my comments...
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib> // Unneeded since other headers here already include this
#include <fstream>
using namespace std; // NEVER globally use the entire standard namespace!
const int MAX_LOG_SIZE = 7584; // Can be declared 'constexpr'
const string LOGFILE ="crimes.dat";
const string OUTPUT_FILE ="crimesorted.log";
/*
NOTE:
> It often looks a lot cleaner to have a header part of your code
and then define your functions seperately. This is good practice
for when you need to start using header files with big projects
*/
struct CrimeInfo
{ // Can declare all variables by only listing type once if they're all the same type
string Crimedescr;
string Date;
string Time;
string Address;
string Grid;
string Latitude;
string Longitude;
};
CrimeInfo crimeList [MAX_LOG_SIZE]; // This should be in 'main()'
/*
This should not be its own function.
Making too many function can make things look a bit confusing.
Here, this is only 4 lines of code, so you shouldn't be making
an entire function for it.
*/
void openInputFile(ifstream& inputFile, string inputFilename)
{
inputFile.open(inputFilename.c_str());
while (inputFile.fail())
{
cout << "Failed to open input file: " << inputFilename << ".\n";
exit(1);
}
};
/*
This should also just be written out where its used. There's
no need to make a whole function for a task like this.
ERROR HERE:
> LOGFILE is NOT an std::ifstream! It is a std::string!
*/
void getLogEntry(ifstream &LOGFILE, CrimeInfo &entry)
{
getline(LOGFILE, entry.Date);
getline(LOGFILE, entry.Time);
getline(LOGFILE, entry.Address);
getline(LOGFILE, entry.Grid);
getline(LOGFILE, entry.Crimedescr);
getline(LOGFILE, entry.Latitude);
getline(LOGFILE, entry.Longitude);
}
/*
This should not be its own function.
Making too many function can make things look a bit confusing.
Here, this is only 4 lines of code, so you shouldn't be making
an entire function for it.
*/
void openOutputFile(ofstream& outputFile, string outputFilename)
{
outputFile.open(outputFilename.c_str());
if (outputFile.fail())
{
cout << "Failed to open output file: " << outputFilename << ".\n";
exit(2);
}
}
// It's a good idea to use some sort of documentation style for functions
void outputLogFile(
// Declare variables const when they aren't modified
/* (const) */ string outputFilename,
/* (const) */ CrimeInfo arr[],
/* (const) */ int size)
{
ofstream outputLogFile;
openOutputFile(outputLogFile, outputFilename); // Just write out the code
outputLogFile << "\nCrime log sort ^^:\n\n";
for (int i = 0; i < size; i++)
{
/*
You only need to declare the name of the stream one time
e.g.
outputLogFile << thing1 << thing2
<< thing3 << thing4 << thing5
<< thing6
<< endl;
*/
outputLogFile << arr[i].Date << " ";
outputLogFile << arr[i].Address << " (";
outputLogFile << arr[i].Longitude << " ";
outputLogFile << arr[i].Latitude << " ";
outputLogFile << arr[i].Time << " ";
outputLogFile << arr[i].Grid << " ";
outputLogFile << arr[i].Crimedescr << ""; // Empty quotes not needed here
outputLogFile << endl;
}
outputLogFile.close();
}
int main()
{
// What data are you outputting?
outputLogFile(OUTPUT_FILE, crimeList, MAX_LOG_SIZE);
// Are you trying to load the data you just outputted?
for (int i =0; i < MAX_LOG_SIZE; i++)
{ // I added these braces, but it's a good idea to always have braces
// You have not declared 'inputFile' anywhere
getLogEntry(inputFile, crimeList[i].Date);
}
}
Instead of leaving you to have to figure all that out on your own (I know how frustrating that can be), I went ahead and wrote your program how I'd do it. I tried to put comments in a lot of places to make it easy to follow along with. If you have any questions about it, feel free to ask me.
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
/*
If you're using C++17, the lines below can just become one line:
using std::cin, std::cout, std::endl, std::ifstream,
std::ofstream, std::string, std::getline;
*/
using std::cin;
using std::cout;
using std::endl;
using std::ifstream;
using std::ofstream;
using std::string;
constexpr int MAX_LOG_SIZE = 7584;
const string LOGFILE_NAME = "crimes.dat";
// I'm assuming: inputFile ^^^
// outputFile vvv
const string OUTPUT_FILE_NAME = "crimesorted.log";
/*
NOTE: If you're trying to export data to "crimesorted.log"
and then load it back into the program through "crimes.dat",
that will be a problem. I say this because the main method
in your original code, this is the order you had it in.
*/
// [BEGIN] Function Prototypes
// Structure of strings based on info from crimes.dat
struct CrimeInfo
{
string Crimedescr, Date, Time, Address,
Grid, Latitude, Longitude;
};
/** (This is JavaDoc-style documentation)
[Purpose of function here]
#param outputFile [Describe paramater here]
#param arr[] [Describe parameter here]
#param size_of_arr Size of 'arr[]'
*/
void outputLogFile(
ofstream& outputFile, // Changed to 'std::ofstream&' because I declare this in 'main()'
const CrimeInfo arr[],
const int size_of_arr);
// [END] Function Prototypes
int main()
{
// Create std::ifstream and open a file
ifstream file_to_load;
file_to_load.open(LOGFILE_NAME);
// Constructing and using 'crimeList' here allows the size to be known in
// this scope. However, if it's passed to a function, it's passed as a pointer
CrimeInfo crimeList[MAX_LOG_SIZE];
// Check if file was open and do stuff with it
if (file_to_load.is_open())
{ // File was opened
for (int i = 0; i < MAX_LOG_SIZE; i++)
{
getline(file_to_load, crimeList[i].Date);
getline(file_to_load, crimeList[i].Time);
getline(file_to_load, crimeList[i].Address);
getline(file_to_load, crimeList[i].Grid);
getline(file_to_load, crimeList[i].Crimedescr);
getline(file_to_load, crimeList[i].Latitude);
getline(file_to_load, crimeList[i].Longitude);
}
file_to_load.close(); // Close file
}
else
{ // File could not be
cout << "Could not open file: " << LOGFILE_NAME << endl;
return 1;
}
// Create std::ofstream and output the log
ofstream outputFile;
outputFile.open(OUTPUT_FILE_NAME);
// Check if 'outputFile' opened OUTPUT_FILE_NAME successfully
if(outputFile.is_open())
{ // File was opened
outputLogFile(outputFile, crimeList, MAX_LOG_SIZE);
outputFile.close();
}
else
{ // File could not be opened
cout << "Could not open file: " << OUTPUT_FILE_NAME << endl;
return 1;
}
}
// Function definition for outputLogFile()
void outputLogFile(
ofstream &outputFile,
const CrimeInfo arr[],
const int size_of_arr)
{
outputFile << "\nCrime log sort ^^:\n\n";
for (int i = 0; i < size_of_arr; i++)
{
outputFile
<< arr[i].Date << '\n' // Newlines may look better than spaces here
<< arr[i].Address << " ("
<< arr[i].Longitude << ", "
<< arr[i].Latitude << ")\n"
<< arr[i].Time << '\n'
<< arr[i].Grid << '\n'
<< arr[i].Crimedescr
<< endl;
}
}
I am trying to write some string data to a .txt file that i read from the user but after doing so, the program shuts down instead of continuing and when i check the results inside the .txt file i see some part of the data and then some gibberish, followed by an assertion failure error! Here's the code:
#include "std_lib_facilities.h"
#include <fstream>
using namespace std;
using std::ofstream;
void beginProcess();
string promptForInput();
void writeDataToFile(vector<string>);
string fileName = "links.txt";
ofstream ofs(fileName.c_str(),std::ofstream::out);
int main() {
// ofs.open(fileName.c_str(),std::ofstream::out | std::ofstream::app);
beginProcess();
return 0;
}
void beginProcess() {
vector<string> links;
string result = promptForInput();
while(result == "Y") {
for(int i=0;i <= 5;i++) {
string link = "";
cout << "Paste the link skill #" << i+1 << " below: " << '\n';
cin >> link;
links.push_back(link);
}
writeDataToFile(links);
links.clear(); // erases all of the vector's elements, leaving it with a size of 0
result = promptForInput();
}
std::cout << "Thanks for using the program!" << '\n';
}
string promptForInput() {
string input = "";
std::cout << "Would you like to start/continue the process(Y/N)?" << '\n';
std::cin >> input;
return input;
}
void writeDataToFile(vector<string> links) {
if(!ofs) {
error("Error writing to file!");
} else {
ofs << "new ArrayList<>(Arrays.AsList(" << links[0] << ',' << links[1] << ',' << links[2] << ',' << links[3] << ',' << links[4] << ',' << links[5] << ',' << links[6] << ',' << "));\n";
}
}
The problem lies probably somewhere in the ofstream writing procedure but i can't figure it out. Any ideas?
You seem to be filling a vector of 6 elemenents, with indices 0-5, however in your writeDataToFile function are dereferencing links[6] which is out of bounds of your original vector.
Another thing which is unrelated to your problem, but is good practice:
void writeDataToFile(vector<string> links)
is declaring a function which performs a copy of your vector. Unless you want to specifically copy your input vector, you most probably want to pass a const reference, like tso:
void writeDataToFile(const vector<string>& links)
In my program, I save high scores along with a time in minutes and seconds. In my code, I currently store this as two ints in a struct called highscore. However, this is a little tedious when it comes to formatting when I display the output. I want to display the times as 12:02 not 12:2. I have a variable already made called string clock throughout my game, it is already formatted with the colon, all I want to do is add that inside my text file.
How can I refactor my code to have a single variable for the timestamp, which will be correctly formatted? I want to be able to write my data into the file by directly calling the structure.
// Used for Highscores
struct highscore
{
char name[10];
int zombiesKilled;
// I would like these to be a single variable
int clockMin;
int clockSec;
char Date[10];
};
// I write the data like this:
highscore data;
// ...
data[playerScore].clockMin = clockData.minutes;
data[playerScore].clockSec = clockData.seconds;
streaming = fopen( "Highscores.dat", "wb" );
fwrite( data, sizeof(data), 1 , streaming);
// ...
It seems that you want to simply just write a C-string or std::string to a file using C's fwrite() function.
This should be quite easy, given that your C-string is in ASCII-conforming format (no Unicode funny business):
//It appears you want to use C-style file I/O
FILE* file = NULL;
fopen("Highscores.dat", "wb");
//std::string has an internal C-string that you can access
std::string str = "01:00";
fwrite(str.c_str(), sizeof(char), sizeof(str.c_str()), file);
//You can also do this with regular C strings if you know the size.
We can also choose to try and use C++-style file I/O for cleaner interfaces.
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
int main() {
std::string str = "00:11";
std::ofstream file("example.txt");
if (file.good()) {
file << str;
std::cout << "Wrote line to file example.txt.\n";
}
file.close();
//Let's check if we actually wrote the file.
std::ifstream read("example.txt");
std::string buffer;
if (read.good())
std::cout << "Opened example.txt.\n";
while(std::getline(read, buffer)) {
std::cout << buffer;
}
return 0;
}
Additionally, there are data types in <chrono> that can prove quite helpful for times like there.
If you want to be able to do this:
file << data_struct;
then it would make sense for you to create an operator overload for std::ostream.
You can experiment with time functions. And reading/writing structures.
The right way however is to use c++ basic file storage instead of dumping binar data.
struct highscore
{
char name[10];
int n;
std::time_t dateTime;
};
int main()
{
int total_seconds = 61;
char buf[50];
sprintf(buf, "minutes:seconds=> %02d:%02d", total_seconds / 60, total_seconds % 60);
cout << buf << endl;
std::time_t timeNow = std::time(NULL);
std::tm timeFormat = *std::localtime(&timeNow);
cout << "Current date/time " << std::put_time(&timeFormat, "%c %Z") << endl;
highscore data;
//write data:
{
FILE *streaming = fopen("Highscores.dat", "wb");
strcpy(data.name, "name1");
data.n = 1;
data.dateTime = std::time(NULL);
fwrite(&data, sizeof(data), 1, streaming);
strcpy(data.name, "name2");
data.n = 2;
data.dateTime = std::time(NULL);
fwrite(&data, sizeof(data), 1, streaming);
fclose(streaming);
}
//read data:
{
FILE *streaming = fopen("Highscores.dat", "rb");
fread(&data, sizeof(data), 1, streaming);
cout << "reading:\n";
cout << data.name << endl;
cout << data.n << endl;
timeFormat = *std::localtime(&data.dateTime);
cout << std::put_time(&timeFormat, "%c %Z") << endl;
cout << endl;
fread(&data, sizeof(data), 1, streaming);
cout << "reading:\n";
cout << data.name << endl;
cout << data.n << endl;
timeFormat = *std::localtime(&data.dateTime);
cout << std::put_time(&timeFormat, "%c %Z") << endl;
cout << endl;
fclose(streaming);
}
return 0;
}
How do you create multiple new class objects using the default class constructor?
For a project I am having to write a program that writes three class objects into a file. That I have done... The next part is being able to read the data back into three separate class objects using a readData function and then displaying the data. I am completely lost at how to do this so I don't have any code in the readData function.
Here is an example of what the object looks like when it is being written to the file.
employee name(21, "first last", "45 East State", "661-9000", 30, 12.00);
Here is the bulk of my code the employee class is fairly basic but here is the default class constructor.
employee::employee ();
employee::employee(int locEmpNumber, string locName, string locaddress, string locphone, double locHrWorked, double locHrWage)
#include "employee.h"
#include <string>
#include <iomanip>
#include <iostream>
#include <fstream>
using namespace std;
void writeData (const employee& e);
void readData (const employee& e);
void printCheck (const employee& e);
int main( )
{
//Declarations
const int ONE = 1;
const int TWO = 2;
int userInput;
cout << "This program has two options:" << endl;
cout << "1 - Create a data files called 'EmployeeInfo.txt', or" << endl;
cout << "2 - Read data from a file and print paychecks." << endl;
cout << "Please enter (1) to create a file or (2) to print checks: ";
cin >> userInput;
if (userInput == ONE)
{
//Create employee objects:
employee joe(37, "Joe Brown", "123 Main St.", "123-6788", 45, 10.00);
employee sam(21, "Sam Jones", "45 East State", "661-9000", 30, 12.00);
employee mary(15, "Mary Smith", "12 High Street", "401-8900", 40, 15.00);
ofstream empFile ("EmployeeInfo.txt");
//Employee objects to write themselves out to the file.
writeData(joe);
writeData(sam);
writeData(mary);
//Close the file.
empFile.close();
//Print an message that creation of the file is complete.
system("CLS");
cout << "\nCreation of 'EmployeeInfo.txt' has completed.\n";
cout << "\nYou can now run option 2.\n";
//Exit.
system("PAUSE");
return 0;
}
else if (userInput == TWO)
{
//Create three new Employee objects, using the default Employee constructor.
//Open the file that you just saved.
//Have each object read itself in from the file.
//Call the printCheck( ) function for each of the three new objects, just as you did in the previous project.
}
else
{
system("CLS");
cout << "Incorrect entry.... Please try again and follow directions closely! \n" << endl;
system("PAUSE");
return 0;
}
}
void writeData(const employee& e)
{
fstream empFile;
empFile.open ("EmployeeInfo.txt", ios::app);
empFile << e.getEmpNumber() << "\n";
empFile << e.getName() << "\n";
empFile << e.getAddress() << "\n";
empFile << e.getPhone() << "\n";
empFile << e.getHrWorked() << "\n";
empFile << e.getHrWage() << "\n";
}
void readData(const employee& e)
{
fstream empFile;
empFile.open ("EmployeeInfo.txt", ios::in);
if(empFile.fail())
{
cout << "File could not be open. Please try option 1 then option 2.\n" << endl;
return;
}
}
It's good to see that you have made an effort at solving the problem. However, there is a mismatch between what you set out in your question and some of the comments in your code. It seems clear to me that a key part of your brief is that the employee object itself is required to be able to write itself to the file and to read itself back from the file.
You have written code that will write the contents of the object to the file rather than having the object write itself to the file. It might seem like I'm splitting hairs on this one, but this is the essence of what Object Oriented Programming is about. Encapsulating the functionality within the object itself is the real goal here.
I've included some code below to help you. Hopefully this will make good sense for you.
class employee
{
private:
int _locEmpNumber;
std::string _locName;
std::string _locAddress;
std::string _locPhone;
double _locHrWorked;
double _locHrWage;
public:
employee();
employee(int locEmpNumber, std::string locName, std::string locAddress, std::string locPhone, double locHrWorked, double locHrWage);
//object should be able to save itself as per your project brief.
void writeData(std::ofstream &empFile);
//object should be able to read itself from file as per your project brief
void readData(std::ifstream &empFile);
};
employee::employee()
{
_locEmpNumber = 0;
_locHrWorked = _locHrWage = 0;
}
employee::employee(int locEmpNumber, std::string locName, std::string locAddress, std::string locPhone, double locHrWorked, double locHrWage)
{
_locEmpNumber = locEmpNumber;
_locName = locName;
_locAddress = locAddress;
_locPhone = locPhone;
_locHrWorked = locHrWorked;
_locHrWage = locHrWage;
}
//
//From what I can glean from your brief ...
//Employee objects to write themselves out to the file!!!
void employee::writeData(std::ofstream &empFile)
{
empFile << _locEmpNumber << std::endl;
empFile << _locName << std::endl;
empFile << _locAddress<< std::endl;
empFile << _locPhone << std::endl;
empFile << _locHrWorked << std::endl;
empFile << _locHrWage << std::endl;
}
//
//Again, from what I can glean from your brief ...
//Have each object read itself in from the file!!!
void employee::readData(std::ifstream &empFile)
{
//Normally you would have error handling in a method like this and
//would either return a response that indicates that the operation
//succeded or failed. You might alternatively use exception handling
//or indeed a combination of both.
//
//Normally you would reset all members to initial / empty values before
//reading values into them from your file. In this case we will omit that
//for the purposes of simplicity. The main reason you would reset members
//is to ensure that when reusing an object you don't end up with partial
//data from the current "read" operation mixed with partial data that
//was already in the object before you started reading.
std::string inputStr;
std::getline(empFile, inputStr);
_locEmpNumber = atoi(inputStr.c_str());
std::getline(empFile, _locName);
std::getline(empFile, _locAddress);
std::getline(empFile, _locPhone);
std::getline(empFile, inputStr);
_locHrWorked = atof(inputStr.c_str());
std::getline(empFile, inputStr);
_locHrWage = atof(inputStr.c_str());
}
int main(int argc, char* argv[])
{
//Declarations
const int ONE = 1;
const int TWO = 2;
int userInput;
std::cout << "This program has two options:" << std::endl;
std::cout << "1 - Create a data files called 'EmployeeInfo.txt', or" << std::endl;
std::cout << "2 - Read data from a file and print paychecks." << std::endl;
std::cout << "Please enter (1) to create a file or (2) to print checks: ";
std::cin >> userInput;
if (userInput == ONE)
{
//Create employee objects:
employee joe(37, "Joe Brown", "123 Main St.", "123-6788", 45, 10.00);
employee sam(21, "Sam Jones", "45 East State", "661-9000", 30, 12.00);
employee mary(15, "Mary Smith", "12 High Street", "401-8900", 40, 15.00);
std::ofstream empFile ("EmployeeInfo.txt");
//Employee objects to write themselves out to the file.
joe.writeData(empFile);
sam.writeData(empFile);
mary.writeData(empFile);
// writeData(joe);
// writeData(sam);
// writeData(mary);
//Close the file.
empFile.close();
//Print an message that creation of the file is complete.
system("CLS");
std::cout << "\nCreation of 'EmployeeInfo.txt' has completed.\n";
std::cout << "\nYou can now run option 2.\n";
//Exit.
system("PAUSE");
return 0;
}
else if (userInput == TWO)
{
//Create three new Employee objects, using the default Employee constructor.
employee joe;
employee sam;
employee mary;
//Open the file that you just saved.
std::ifstream empFile("EmployeeInfo.txt");
//Have each object read itself in from the file.
joe.readData(empFile);
sam.readData(empFile);
mary.readData(empFile);
empFile.close();
//Call the printCheck( ) function for each of the three new objects, just as you did in the previous project.
//I'll leave it to you to add this yourself.
}
else
{
system("CLS");
std::cout << "Incorrect entry.... Please try again and follow directions closely! \n" << std::endl;
system("PAUSE");
return 0;
}
return 0;
}