I've made a program using which we can add records in a file is an
order, but the displaying of the file after adding the record is
not working.
If I add "|ios::app" in "ofstream fo" to open the file in append
mode, the displaying by "fin" is working.
Why is it so? I'm using mingw4.8.1
#include<fstream>
#include<iostream>
#include<stdio.h>
class c{
public:
int r;
char nm[20];
};
using namespace std;
int main()
{
c a,b;
ifstream fi("old.txt",ios::binary);
ofstream fo("new.txt",ios::binary); // if |ios::app is added here, the
// display by fin below is working fine
cout<<"Enter roll\t";
cin>>b.r;
cout<<"Enter name\t";
fflush(stdin);
gets(b.nm);
int w=0;
while(true)
{
fi.read((char *)&a,sizeof(a));
if(fi.eof()) break;
if(b.r<a.r&&w==0)
{
fo.write((char *)&b,sizeof(b));
w++;
}
else
fo.write((char *)&a,sizeof(a));
}
ifstream fin("new.txt",ios::binary); // this is not working of the //ios:: is not added in the ofstream fo
while(true)
{
fin.read((char *)&a,sizeof(a));
if(fin.eof()) break;
cout<<a.r<<endl;
puts(a.nm);
}
return 0;
}
This is the correct code closest to what you want
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct c {
int roll;
string name;
};
int main() {
c a, b;
ifstream fi("old.txt");
ofstream fo("new.txt");
cout << "Enter roll no. and name" << endl;
cin >> b.roll >> b.name;
while (fi >> a.roll >> a.name) {
if (b.roll < a.roll)
fo << b.roll << " " << b.name << endl;
else
fo << a.roll << " " << a.name << endl;
}
fi.close();
fo.close();
ifstream fin("new.txt");
while (fin >> a.roll >> a.name)
cout << a.roll << " " << a.name << endl;
fin.close();
return 0;
}
It is my understanding that if you use ios::app you must also indicate ios::out try ios::app | ios::out | ios::binary and see if that helps.
Related
I am trying to insert object in file and then read the object to display the student data but when It goes to display program just goes in infinite loop and starts displaying 0 which I have initialized in constructor.I am simply not getting what is happening. I am using visual studio 17 just in case anyones wondering. I even tried to create a new file named Student.txt in same directory as the program but it won't work. Can somone explain me what I am doing wrong?
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
//class to handle individual record
class Student
{
public:
char name[20];
int year;
char division;
char address[50];
int rollno;
Student()
{
strcpy_s(name," ");
strcpy_s(address, " ");
rollno = 0;
year = 0;
division = 0;
}
};
class operations
{
public:
void insertdata();
void printg();
};
void operations::insertdata()
{
int n;
cout << "\nEnter how many student data you want to insert:";
cin >> n;
fstream fin;
Student obj;
fin.open("Student.txt", ios::in | ios::out | ios::binary| ios::trunc);
if (!fin)
{
cout<<"\nFILE NOT Opened!";
}
for (int v = 0; v < n; v++)
{
cout << "\nEnter Roll no:";
cin >> obj.rollno;
cout << "\nEnter Name:";
cin.ignore();
cin >> obj.name;
cout << "\nEnter year:";
cin >> obj.year;
cout << "\nEnter division:";
cin >> obj.division;
cout << "\nEnter Address:";
cin.ignore();
cin >> obj.address;
fin.seekp(0, ios::end);
fin.write((char*)&obj, sizeof(obj));
}
fin.close();
}
void operations::printg()
{
Student obj;
fstream fin("Student.txt", ios::in | ios::out | ios::binary);
fin.seekg(0, ios::beg);
fin.read((char*)&obj, sizeof(obj));
if (!fin)
{
cout << "\n FIle doenst exist";
}
while (!fin.eof())
{
cout << "\n" << obj.name;
cout << "\n" << obj.year;
cout << "\n" << obj.division;
}
fin.close();
}
int main() {
operations obj;
obj.insertdata();
obj.printg();
system("pause");
return 0;
}
A few wrong things:
Writing objects like fin.write((char*)&obj, sizeof(obj)); is a bad idea. A compiler may decide to have different padding between members at any moment for your Student objects, so your file format is like a quantum particle: you don't really know how the file was laid out.
strcpy_s takes 3 parameters, not 2. Anyway, do not use them, they are not really portable (even if they are in the C standard).
Your paths are wrong, so the file will not open (as Sam explains in the comment).
Even if you succeeded in opening a file, in operations::printg() you are not reading the file, so you will not get any data.
Why do you have an operations class? I guess it is intended to be expanded in the future, but seems weird. If you do not intend to have state, use a namespace instead.
I have created a class Scholar with attributes: string name, int id, char grade. Then, I had written the data in text file in binary mode using program P1. I had another program P2 which inserts a new data in between previous data.
It shows data (using program P1) when I initially created the text file with some objects. But, when I inserted a new data (using program P2), the attributes id and grade appears but, the attribute name went missing.
The Scholar class code:
#ifndef SCHOLAR_H
#define SCHOLAR_H
#include <iostream>
#include <cstdio>
using namespace std;
class Scholar {
int id;
string name;
char grade;
public:
void read_data() {
cout << "\nEnter ID: ";
cin >> id;
string temp;
getline(cin, temp);
cout << "Enter name: ";
getline(cin, name);
cout << "Enter grade: ";
cin >> grade;
}
void print_data() {
cout << "\nID: " << id << " | Name: " << name << " | Grade: " << grade;
}
int modify_data();
int _id() {
return id;
}
string _name() {
return name;
}
char _grade() {
return grade;
}
};
#endif // SCHOLAR_H
Program P1:
#include "MyHeaderFiles/Scholar.h"
#include <fstream>
#include <cstdlib>
#include <cctype>
int main() {
system("cls");
Scholar sch;
fstream fs;
fs.open("SchDB.txt", ios::out | ios::in | ios::binary | ios::trunc);
if(!fs) {
cerr << "File not found!";
system("PAUSE");
}
char reply;
do {
sch.read_data();
fs.write((char*) &sch, sizeof(sch));
cout << "Do you want to add another scholar (y/n) : ";
cin >> reply;
} while(tolower(reply) == 'y');
fs.seekg(0);
cout << "\nFile content\n------------" << endl;
while(!fs.eof()) {
fs.read((char*) &sch, sizeof(sch));
if(fs.eof()) break;
sch.print_data();
}
fs.close();
cout << endl;
return 0;
}
The initial image of output when I hadn't inserted any new data:
You can see the names!
Program P2:
#include "MyHeaderFiles/Scholar.h"
#include <fstream>
#include <cstdlib>
int main() {
system("cls");
Scholar sch;
Scholar newSch;
ofstream fout;
ifstream fin;
fout.open("Temp.txt", ios::out | ios::binary);
fin.open("SchDB.txt", ios::in | ios::binary);
char last = 'y';
int pos;
cout << "\nYou have to enter data of a new student." << endl;
newSch.read_data();
fin.seekg(0);
cout << "\nFile content\n------------" << endl;
while(!fin.eof()) {
pos = fin.tellg();
fin.read((char*) &sch, sizeof(sch));
if(sch._id() > newSch._id()) {
fout.write((char*) &newSch, sizeof(newSch));
last = 'n';
break;
} else {
fout.write((char*) &sch, sizeof(sch));
}
}
if(last == 'y') {
fout.write((char*) &newSch, sizeof(newSch));
} else if(!fin.eof()) {
fin.seekg(pos);
while(!fin.eof()) {
fin.read((char*) &sch, sizeof(sch));
if(fin.eof()) break;
fout.write((char*) &sch, sizeof(sch));
}
}
fin.close();
fout.close();
remove("SchDB.txt");
rename("Temp.txt", "SchDB.txt");
fin.open("SchDB.txt", ios::in | ios::binary);
fin.seekg(0);
while(!fin.eof()) {
fin.read((char*) &sch, sizeof(sch));
if(fin.eof()) break;
sch.print_data();
}
fin.close();
cout << endl;
return 0;
}
The later image when I used the program P2 to insert new data:
And, now you can see only the name attribute is missing!
I am using Code::Blocks IDE and GNU GCC Compiler.
Can anybody explain me why the string isn't showing up?
#include "stdafx.h"
#include<iostream>
#include<fstream>
using namespace std;
class Motherboards
{
char name[50];
char chip[50];
float price;
public:
void getdata()
{
cout << "Enter name :\n";
cin.getline(name, 50);
cout << "Chip :\n";
cin.getline(chip, 50);
cout << "Price:\n";
cin >> price;
}
void putdata()
{
cout << name << endl;
cout << chip << endl;
cout << price << endl;
}
}M;
int main()
{
long pos;
fstream input("Motherboard.txt", ios::in | ios::out | ios::app);
M.getdata();
pos=input.tellg();
input.seekg(pos);
input.write((char*)&M,sizeof(M));
M.putdata();
return 0;
}
I can`t enter the data properly to the Motherboard.dat or the Motherboard.txt. I have included pictures of when i run the program with one more edit to the above code and the output is not as expected. I am a beginner
so please explain in detail on how to correct it.
Text:
Asus X99 #GAsus Z97 #œFÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍ
1st Run
2nd Run after edit which i actually want to do
Below code is able to send a single student information to a file at once. How can it modified to send more records one after another without exiting and re-opening the program. I'm new for this. Kindly help.
#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <windows.h>
#include <sstream>
#include <algorithm>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include <iomanip>
#include <dos.h>
using namespace std;
string userName;
string passWord;
string selection;
int option;
struct patientinfo {
string PatientFname;
string PatientLname;
int Age;
int ContactNo;
string TreatmentType;
string AppDate;
string AppTime;
int eReciptId;
};
int num;
patientinfo emp[50];
void makeBooking()
{
ofstream outputFile;
outputFile.open("smt.bin", std::ofstream::in | std::ofstream::out | std::ofstream::app);
int i=num;
num+=1;
cout<< endl << endl << endl << endl << endl << endl
<< setw(30)<<"First Name : ";
cin>>emp[i].PatientFname;
outputFile <<emp[i].PatientFname <<",";
cout<< setw(30)<<"Last Name : ";
cin>>emp[i].PatientLname;
outputFile <<emp[i].PatientLname <<",";
cout<< setw(30)<<"Age : ";
cin>>emp[i].Age;
outputFile <<emp[i].Age <<",";
}
int main ()
{
makeBooking();
return 0;
}
Considering you have 50 students to whom you want to send information you should call the makeBooking function 50 times. So changing your main in
int main ()
{
for (int i = 0; i < 50; i++) {
makeBooking();
}
return 0;
}
should do the trick.
However, a more elegant solution would be to send the index i as a parameter in your function. So the code would be:
patientinfo emp[50];
void makeBooking(int i)
{
ofstream outputFile;
outputFile.open("smt.bin", std::ofstream::in | std::ofstream::out | std::ofstream::app);
// int i=num; you don't need these anymore
// num+=1;
cout<< endl << endl << endl << endl << endl << endl
<< setw(30)<<"First Name : ";
cin>>emp[i].PatientFname;
outputFile <<emp[i].PatientFname <<",";
cout<< setw(30)<<"Last Name : ";
cin>>emp[i].PatientLname;
outputFile <<emp[i].PatientLname <<",";
cout<< setw(30)<<"Age : ";
cin>>emp[i].Age;
outputFile <<emp[i].Age <<",";
}
int main ()
{
char response;
for (int i = 0; i < 50;) {
cout << "Do you want to add another person?";
cin >> response;
if (response == 'y')
makeBooking(i++);
else if (respinse == 'n')
break;
else
cout << "Undefined response";
}
return 0;
}
I have a program in c++ which is used to read some text from a .txt file using fstream functions. But on output screen, it is showing an extra output of while loop which is undesirable.So if tt.txt contains the data
ss
123
then output is
Name ss
roll no 123
name
roll 123
Code:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
#include<stdio.h>
void student_read()
{
clrscr();
char name[30];
int i,roll_no;
ifstream fin("tt.txt",ios::in,ios::beg);
if(!fin)
{
cout<<"cannot open for read ";
return;
}
while(!fin.eof())
{
fin>>name;
cout<<endl;
fin>>roll_no;
cout<<endl;
cout<<"Name is"<<"\t"<<name<<endl;
cout<<"Roll No is"<<roll_no<< endl;
}
}
void main()
{
clrscr();
cout<<"Students details is"<<"\n";
student_read();
getch();
}
See the C++ FAQ for help with I/O: http://www.parashift.com/c++-faq/input-output.html
#include <iostream>
#include <fstream>
void student_read() {
char name[30];
int roll_no;
std::ifstream fin("tt.txt");
if (!fin) {
std::cout << "cannot open for read ";
return;
}
while(fin >> name >> roll_no) {
std::cout << "Name is\t" << name << std::endl;
std::cout << "Roll No is\t" << roll_no << std::endl;
}
}
int main() {
std::cout << "Students details is\n";
student_read();
}