Click here to Skip to main content
15,920,503 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
The file is storing some junk values, What can be done?

What I have tried:

C++
//define class student
class student{
public:
int n,nosub;
char day[10];
char subject[10],classtime[10],classroom[10],startdate[10],enddate[10];
//create or add new entries
public:
void getdata()
{
//input from user
int n,nosub;
char day[10];
char subject[10],classtime[10],classroom[10],startdate[10],enddate[10];
//user will enter the number of days
cout<<"enter the number of days: "<<endl;
cin>>n;
for(int i =0; i<n; i++){
cout<<="" "day="<<endl;
cin>>day;
{
  cout<<" enter="" the="" number="" of="" subjects="<<endl;
  cin>>nosub;
for(int j =0; j<nosub; j++){
cout<<" \nenter="" subject="" :="" ";
cin="">>subject[j];
cout<<"\n classtime  :  ";
cin>>classtime[j];
cout<<"\n classroom  :  ";
cin>>classroom[j];
cout<<"\n startdate :  ";
cin>>startdate[j];
cout<<"\n enddate:  ";
cin>>enddate[j];
}
}}}
};
student stu;
//displaying the data from the file this can be used for display
void display()
 {
  //opening the file in read mode
  ifstream myfile("student1.txt");
  //vector declaration
  vector<string>v;
  string p;
  //read the next line from the file till it reaches the end
  while(getline(myfile,p))
  {
  v.push_back(p);
}
//display the content of the file
copy(v.begin(),v.end(),ostream_iterator<string>(cout,"\n"));
 }
int main()
{
//decalre objects from class student
student stu;
bool quit=true;

system("CLS");
int option;
cout<<"ADD DATA"<<endl;
cout<<"display"<<endl;
cout<<"quit"<<endl;
cout<<"enter the="" choice"<<endl;
cin="">>option;
switch (option){
case 1:
{
//opening file in write mode
char day[10];
char subject[10],classtime[10],classroom[10],startdate[10],enddate[10];
fstream myfile;
myfile.open("student1.txt",ios::in|ios::out);
if(!myfile)
{
cout<<"file not created";

}
else
{
//calling the function
stu.getdata();
//writing into the file
myfile<
Posted
Updated 16-Dec-21 1:35am
v2

1 solution

The elements in your student structure are all character variables of length 10, so they will only be able to hold a single item that is no longer than 9 characters. But your code does the following:
C++
cin >> subject[j];

which will read a single character and store it at the jth character position of that array. You need to change those items to std::string types in order to capture multiple values.
 
Share this answer
 
Comments
CPallini 16-Dec-21 7:47am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900