I have to create a simple code that is supposed to create a .txt file as an output, containing a list fo notations with this format. (time ; topic ; comment) the code has to run a loop using a struct function showed below:
struct annotation_t {
string topic;
string comment;
time_t stamp;
};
so the user can input the notations as many times he wants till he decides to go out. This is what I did so far.
#include <iostream>
#include <string>
#include <ctime>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
struct annotation_t {
string topic;
string comment;
time_t stamp;
};
int main()
{
int q = 0;
std::vector<annotation_t> obj;
do
{
annotation_t temp = {};
cout<< "input your topic: ";
cin >> temp.topic ;
cout<< "input yourfeedback: ";
cin >> temp.comment ;
cout<< "input your time stamp: ";
cin >> temp.stamp ;
cout<< "exit?";
cin >> q;
obj.push_back(temp);
} while (q != 0);
ofstream myfile("annotation.txt");
char time[1000];
for(int i = 0;i<50;i++)
{
struct annotation_t obj[i];
myfile<<obj[i].stamp <<" "; // write in file
myfile<<obj[i].topic <<" ";// write in file
myfile<<obj[i].comment; // write in file
myfile<<"\n";
}
cout<<"\nFile Created with Data with name annotation.txt \n";
myfile.close();
system("Pause");
}
I have a problem when it come to exit. if I input any value( even 0) I get a segmentation fault so i am not able to quit the loop and save my file in the txt, or re run it if I want to input more.. Let me know your thoughts.thanks
You have problem with declaration 'obj' object. This is wrong :
struct annotation_t obj[i];
Try this instead :
#include <iostream>
#include <string>
#include <ctime>
#include <fstream>
#include <cstdlib>
using namespace std;
struct annotation_t {
string topic;
string comment;
time_t stamp;
};
int main()
{
int q = 0;
struct annotation_t obj[1000]; //msf
int i=0; //msf
do
{
cout<< "input your topic";
cin >> obj[i].topic ;
cout<< "input yourfeedback";
cin >> obj[i].comment ;
cout<< "input your time stamp";
cin >> obj[i].stamp ;
cout<< "exit?";
cin >> q ;
i++; //msf
} while (q != 0);
ofstream myfile("annotation.txt");
int count=i; //msf
for(i = 0;i<count;i++) //msf
{
myfile<<obj[i].stamp <<" "; // write in file
myfile<<obj[i].topic <<" ";// write in file
myfile<<obj[i].comment; // write in file
myfile<<"\n";
}
cout<<"\nFile Created with Data with name annotation.txt \n";
myfile.close();
system("Pause");
}
I changed your code in many positions that I commented with '//msf'. I don't have C++ compiler in hand then I hope it will be compiled without errors.