To write marks and roll n details of students of a class into a file..The output contains only the last entered data.Why is that so?
#include<fstream.h>
int main()
{
ofstream fout;
fout.open("File1",ios::out);
char cch;
fout<<"ROLLNO\t"<<"MARKS"<<"\n";
int rollno,marks;
do
{
cout<<"Enter the rollno1";
cin>>rollno;
cout<<"Enter the marks";
cin>>marks;
fout<<rollno<<"\t"<<marks<<"\n";
cout<<"Do you want to insert more?" ;
cin>>cch;
}
while(cch=='y');
fout.close();
ifstream fin;
char ch;
fin.open("File1",ios::in);
fin.seekg(0);
fin.tellg();
while(fin)
{
fin>>rollno;
fin>>marks;
cout<<rollno<<"\t"<<marks<<"\n";
}
fin.close();
return 0;
}
Please help me find the error.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Q :Why is not this code working properly?
I have implemented file handling in C++ language.
I have created a complete file of the car. Through this code, we can store new data, delete old one, search a particular data about the car.The problem is that this code compiles successfully but during runtime, its execution stops and display an error message. I request kindly help me in removing runtime error from this code.
CODE:
#include<iostream>
#include<string.h>
#include<conio.h>
#include<fstream>
using namespace std;
struct car
{
char name[20];
int model;
string color;
int car_id;
string size;
float weight;
int price;
};
void getdata(car&); //function declaration
void showdata(car&); //function declaration
void searchdata(); //function declaration
void deleterecord(); //function declaration
void modify(); //function declaration
void readdata(); //function declaration
void writedata(); //function declaration
int main()
{
char ch;
cout<<"\nEnter w to write record ";
cout<<"\nEnter r to read record";
cout<<"\nEnter m to modify record";
cout<<"\nEnter s to search record";
cout<<"\nEnter d to delete record";
cout<<"\n\nEnter your choice :";
cin>>ch;
switch(ch)
{
case 'w':
{
writedata();
break;
}
case 'r':
{
readdata();
break;
}
case 's':
{
searchdata();
break;
}
case 'd':
{
deleterecord();
break;
}
case 'm':
{
modify();
break;
}
default:
{
cout<<"\nWrong choice";
}
}
return 0;
}
void getdata(car &ccc)
{
cout<<"Please enter name of car :";
cin>>ccc.name;
cout<<"Please enter model number of car:";
cin>>ccc.model;
cout<<"Enter color of car:";
cin>>ccc.color;
cout<<"Enter id number of car:";
cin>>ccc.car_id;
cout<<"Enter size of car :";
cin>>ccc.size;
cout<<"Enter weight of a car :";
cin>>ccc.weight;
cout<<"Enter price of a car :";
cin>>ccc.price;
}
void showdata(car &ccc)
{
cout<<"\nName of car is :";
puts(ccc.name);
cout<<"\nModel number of car is :"<<ccc.model;
cout<<"\nColor of car is :"<<ccc.color;
cout<<"\nID number of car is :"<<ccc.car_id;
cout<<"\nSize of car is :"<<ccc.size;
cout<<"\nWeight of car is :"<<ccc.weight;
cout<<"\nPrice of car is :"<<ccc.price;
}
void writedata()
{
ofstream file;
char ch='y';
car ccc;
file.open("carinformation.dat",ios::binary | ios::out | ios::app);
while(ch=='y'|| ch=='Y')
{
getdata(ccc);
file.write((char*)&ccc,sizeof(ccc));
cout<<"\nDo you want to countine?";
cin>>ch;
}
file.close();
}
void readdata()
{
int count=0;
ifstream file;
car ccc;
file.open("carinformation.dat",ios::binary | ios::in);
if(!file)
{
cout<<"File not found";
exit(0);
}
else
{
file.read((char*)&ccc,sizeof(ccc));
while(!file.eof())
{
showdata(ccc);
file.read((char*)&ccc,sizeof(ccc));
count++;
}
cout<<"Number of records are :"<<count;
}
file.close();
}
void searchdata()
{
car ccc;
ifstream file;
char n_c[20];
cout<<"Enter name of car :";
cin>>n_c;
file.open("carinformation.dat",ios::binary | ios::in);
if(!file)
{
cout<<"File nnot found";
exit(0);
}
else
{
file.read((char*)&ccc, sizeof(ccc));
while(!file.eof())
{
if(strcmp(n_c,ccc.name)==0)
{
showdata(ccc);
}
file.read((char*)&ccc, sizeof(ccc));
}
}
file.close();
}
void modify()
{
car ccc;
fstream file;
char n_c[20];
file.open("carinformation.dat",ios::binary | ios::in | ios::out);
cout<<"\nEnter name of car that should be searched:";
cin>>n_c;
if(!file)
{
cout<<"File not found";
exit(0);
}
else
{
file.read((char*)&ccc,sizeof(ccc));
while(!file.eof())
{
if(strcmp(n_c,ccc.name)==0)
{
file.seekg(0, ios::cur);
cout<<"Enter new record :\n";
getdata(ccc);
int i=file.tellg();
int j=sizeof(ccc);
int k=i-j;
file.seekp(k);
file.write((char*)&ccc, sizeof(ccc));
}
}
}
file.read((char*)&ccc, sizeof(ccc));
file.close();
}
void deleterecord()
{
int count=0;
car ccc;
int c_id;
cout<<"Please enter car id :";
cin>>c_id;
ifstream file;
file.open("carinformation.dat" ,ios::binary| ios::in);
ofstream file2;
file2.open("New carinformation.dat", ios::binary| ios::out);
while(file.read((char*)&ccc,sizeof(ccc)))
{
if(ccc.car_id!=c_id)
{
file2.write((char*)&ccc ,sizeof(ccc));
count++;
}
}
cout<<"Number of records are :"<<count;
file2.close();
count=0;
file2.open("New carinformation.dat", ios::binary| ios::in);
file.read((char*)&ccc,sizeof(ccc));
while(!file.eof())
{
count++;
showdata(ccc);
file.read((char*)&ccc,sizeof(ccc));
}
cout<<"Number of records are :"<<count;
file.close();
file2.close();
remove("carinfomation.dat");
rename("New carinformation.dat", "carinformation.dat");
file.open("carinformation.dat", ios::binary | ios::in);
file.read((char*)&ccc, sizeof(ccc));
while(!file.eof())
{
count++;
showdata(ccc);
file.read((char*)&ccc, sizeof(ccc));
}
cout<<"Number of records are :"<<count;
}
Class car has std::string fields which hold pointers to heap-allocated memory. So saving it to file by writing raw bytes file.write((char*)&ccc,sizeof(ccc)); is not going to work. And, what is more important, reading them later file.read((char*)&ccc, sizeof(ccc)); will fill string objects with invalid pointer values. You need to store fields one by one and read them one by one carefully validating input data.
There is a difference between "string" and "string.h". Delete two characters, ".h" and see if your code works.
<string.h> contains functions like strcpy, strlen for C style null-terminated strings.
<string> contains std::string, std::wstring plus other classes.
You need to initialize your struct, heres an example for your readdata(), look at the changes and figure out how to fix the rest of the program:
void readdata()
{
int count=0;
ifstream file;
car *ccc = new car();
file.open("carinformation.dat",ios::binary | ios::in);
if(!file)
{
cout<<"File not found";
exit(0);
}
else
{
file.read((char*)ccc,sizeof(*ccc));
while(!file.eof())
{
showdata(*ccc);
file.read((char*)ccc,sizeof(*ccc));
count++;
}
cout<<"Number of records are :"<<count;
}
file.close();
}
How can I update data from file in c++ without display the old data? I want to delete specific data and update. For example I want to update the name only and another time update gpa only with delete the old gpa?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int k=0;
string line;
string find;
char name[25];
int id=0;
float gpa=0;
ofstream myfile;
myfile.open("data.txt");
while(k!=3){
cout<<"press 1 for adding data"<<endl;
cout<<"press 2 for update "<<endl;
cin>>k;
if(k==1)
{
cout<<"enter ID "<<endl;
cin>>id;
cout<<"enter Name"<<endl;
cin>>name;
cout<<"enter GPA "<<endl;
cin>>gpa;
myfile<<name<<endl;
myfile<<id<<endl;
myfile<<gpa<<endl<<endl<<endl;
}
if(k==2)
{
cout<<"name u want to update "<<endl;
cin>>find;
ifstream file;
file.open("data.txt");
while (!file.eof() && line!=find)
{
getline(file,line);
}
cout<<"enter ID "<<endl;
cin>>id;
cout<<"enter Name"<<endl;
cin>>name;
cout<<"enter GPA "<<endl;
cin>>gpa;
myfile<<name<<endl;
myfile<<id<<endl;
myfile<<gpa<<endl<<endl<<endl;
}
if(k==3){
myfile.close();
}
}
return 0;
}
First you have to copy all the other records to a temporary file eg. temp.txt and then delete the old file data.txt and rename temp.txt to data.txt. Now write the new record to file data.txt.
code:
if(k==2)
{
cout<<"name u want to update "<<endl;
cin>>find;
ifstream myfile2; //for reading records
myfile2.open("data.txt");
ofstream temp;
temp.open("temp.txt");
while (getline(myfile2, line))
{
if (line != find)
temp << line << endl;
}
myfile2.close();
temp.close();
remove("data.txt");
rename("temp.txt", "data.txt");
//Now add new Record to file
cout<<"enter ID "<<endl;
cin>>id;
cout<<"enter Name"<<endl;
cin>>name;
cout<<"enter GPA "<<endl;
cin>>gpa;
ofstream myfile;
myfile.open("data.txt", ios::app | ios::out);
myfile<<name<<endl;
myfile<<id<<endl;
myfile<<gpa<<endl<<endl<<endl;
}
Line by line read old file and copy lines to a new file. When you find the line which you want to update, change it with your line and copy it to the new file. When you reach EOF, delete old file and rename new file with the name of old file.
It will be something like that:
int replace_line(const char *fname, const char *oldline, const char* newline)
{
int done = 0;
/* Open templorary file */
FILE *newfp = fopen("file.tmp", "a");
if (newfp != NULL)
{
/* Open exiting file */
FILE *oldfp = fopen(fname, "r");
if(oldfp != NULL)
{
ssize_t read;
size_t len = 0;
char * line = NULL;
/* Line-by-line read from exiting file */
while ((read = getline(&line, &len, oldfp)) != -1)
{
if(strstr(line, oldline) == NULL) fprintf(newfp, "%s", line);
else fprintf(newfp, "%s", newline);
}
/* Clean up memory */
fclose(oldfp);
if (line) free(line);
done = 1;
}
fclose(newfp);
remove(fname);
rename("file.tmp", fname);
return done;
}
return 0;
}
I'm making a program that reads a set of names and numbers from one file, expresses the numbers as a ratio, then prints them out to the terminal. I would like to know how I could redirect the output of my functions to a separate file. I have an output file ready, but am unsure of how to redirect my functions' outputs to it.
I didn't include the functions themselves here, which work fine - just the calls.
int main(){
ifstream input;
ofstream output;
string inputname, outputname, name;
int num1, num2;
cout<<"Input file?\n";
cin>>inputname;
cout<<"Output file?\n";
inFile.open(inputname.c_str());
cin>>outputfile;
outFile.open(outputname.c_str());
while(!input.eof()&&!output.eof()){
input>>name>>num1>>num2;
lists (name);
value (num1, num2);
}
input.close()
output.close()
return 0;
}
Have a look at Input/Output with files
Example:
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
As you see, it's very similar to how you're getting the data from fileA.
You have multiple undefined variables (Always test your program before posting!). And you're not checking for eof on the input file correctly. You need to test for eof right after a read operation to see if it succeeded.
int main(){
cout << "Input file?\n";
string inputname;
cin >> inputname;
ifstream input(inputname.c_str());
if (!input) return 1; // handle error however you wish
cout << "Output file?\n";
string outputname;
cin >> outputname;
ofstream output(outputname.c_str());
if (!output) return 2;
while (1) {
string name;
int num1, num2;
input >> name >> num1 >> num2;
if (!input) break;
lists(name);
value(num1, num2);
}
return 0;
}
I was trying out a file handling program to enter a record and in another program try to delete a record. I seem to be getting this error-
no matching function for call to `std::basic_fstream >::open(const char[8], bool)'
for every f.open statement which has an ios::binary declaration in it.
here are the codes
this one if for entering records
#include<iostream.h>
#include<fstream.h>
class employee
{
int code;
char name[20];
char desig[15];
float salary;
public: void get_emp();
};
void employee:: get_emp()
{
cout<<"Code--> ";
fflush(stdin);
cin>>code;
cout<<"Name--> ";
fflush(stdin);
gets(name);
cout<<"Designation--> ";
fflush(stdin);
gets(desig);
cout<<"Salary--> ";
fflush(stdin);
cin>>salary;
}
int main()
{
fstream f;
char ch;
f.open("EMP.dat", ios::binary||ios::app);
employee emp;
cout<<"Enter data:\n";
do
{
emp.get_emp();
f.write((char*)&emp,sizeof(emp));
cout<<"Entre more???(y/n)";
cin>>ch;
}while((ch=='y')||(ch=='Y'));
f.close();
system("pause>null");
return 0;
}
this is for deleting record
#include<iostream.h>
#include<fstream.h>
#include<stdlib.h>
struct employee
{
int code;
char name[20];
char desig[15];
float salary;
}emp;
int main()
{
int xcode; //temporary declaration for employee code
int flag = 0;
fstream ef, tf;
//ef opened for reading, tf opened for transferring all records including modified record
ef.open("EMP.dat", ios::binary|| ios::in);
tf.open("TEMP.dat", ios::binary|| ios::out);
cout<<"Enter employee code to delete:";
cin>>xcode;
while(ef)
{
if(!ef)
exit(0);
ef.read((char*)&emp, sizeof(emp));
if(emp.code == xcode)
{
flag = 1;
}
else
tf.write((char*)&emp, sizeof(emp));
}
ef.close();
tf.close();
if(flag == 1)
cout<<"Record deleted.";
else
cout<<"Not found.";
fstream xf, yf;
//tf opened for reading
xf.open("TEMP.dat", ios::binary||ios::in);
//ef opened for copying all records from TEMP.dat
yf.open("EMP.dat",ios::binary||ios::out);
while(xf)
{
if(!xf)
exit(0);
xf.read((char*)&emp, sizeof(emp));
yf.write((char*)&emp, sizeof(emp));
}
xf.close();
yf.close();
system("pause");
return 0;
}
please help. I need it for my exams.
Thank you
Bitwise OR is a single pipe (|), not a double pipe.
For some reason or another I cannot figure out why the data when opened does not get put into arrays and the program crashes. I have searched around for a answer to no avail. I get the feeling I will be posting a here a few more times before I finish this program!
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string bookTitle [14];
string bookAuthor [14];
int loadData (string pathname);
void showall (int counter);
int main ()
{
int counter;
string pathname;
cout<<"Input the name of the file to be accessed: ";
cin>>pathname;
loadData (pathname);
showall (counter);
cout<<"Press <Enter> to Exit";
cin.ignore();
cin.get();
return 0;
}
int loadData (string pathname) // Loads data from infile into arrays
{
fstream infile;
int counter = 0;
infile.open(pathname.c_str()); //Opens file from user input in main
if( infile.fail() )
{
cout << "File failed to open";
return 0;
}
while (!infile.eof())
{
cout<<"File Opened"; // I get the "File Opened" text and then a crash
infile >> bookTitle [14] ; //takes input and puts into parallel arrays
infile >> bookAuthor [14];
cout<<"Data Put in Arrays";
counter++;
}
infile.close();
}
void showall (int counter) // shows input in title(author) format
{
cout<<bookTitle<<"("<<bookAuthor<<")";
}
Edit: The assignment is to take a file with names in a format such as title
author
title
author
Then it must output the arrays to screen in a title(author) format.
After this I must make it a looping program so a search can be chosen of one of the arrays and returns the entry in a title(author) format.
Here is how the code stands now;
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
string bookTitle [50];
string bookAuthor [50];
int loadData (string pathname);
int showall (int counter);
int main ()
{
string pathname;
int counter=0;
cout<<"Input the name of the file to be accessed: ";
cin>>pathname;
loadData (pathname);
showall (counter);
cout<<"Press <Enter> to Exit";
cin.ignore();
cin.get();
return 0;
}
int loadData (string pathname) // Loads data from infile into arrays
{
fstream infile;
int counter = 0;
infile.open(pathname.c_str()); //Opens file from user input in main
if( infile.fail() )
{
cout << "File failed to open";
return 0;
}
while (!infile.eof())
{
infile >> bookTitle [counter] ; //takes input and puts into parallel arrays
infile >> bookAuthor [counter];
counter++;
}
infile.close();
}
int showall (int counter) // shows input in title(author) format
{
cout<<bookTitle<<"("<<bookAuthor<<")";
return 0;
}
A Quick problem I see is:
infile >> bookTitle [14] ;
infile >> bookAuthor [14];
Is incorrect, What you need is:
infile >> bookTitle[counter];
infile >> bookAuthor [counter];
Also,
The counter variable declared in main() and in loadData() are two different variables. The one declared in main()is never iniitalized at all.
There are many problems with this code.
Main problem
These lines write only into 14th elements of the arrays
infile >> bookTitle [14] ; //takes input and puts into parallel arrays
infile >> bookAuthor [14];
In order to fill the entire array you need to use the counter variable for index:
infile >> bookTitle [counter] ; //takes input and puts into parallel arrays
infile >> bookAuthor [counter];
BTW: if array's size is 14 then the maximum index is 13. So you can't access an element with index 14. And that's probably causes the crash.
Other problems I noticed
counter in main() is not initialized
showall() function takes an argument but does not use it, which is probably the index.
showall() call in main() probably needs to be in a loop, to show all elements.