showing an extra string while reading a file in c++ using fstream - c++

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();
}

Related

string is missing when I read data from a text file in binary mode

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?

Data doesn`t enter properly in .dat file

#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

Displaying content of a file in C++

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.

C++ Program crashes while reading from file using fstream fin

Final project for programming class due tomorrow, any help appreciated, program crashes in this module, after accepting file name. By crash I mean it outputs "This application has requested runtime to terminate it in an unusual way" and then the usual windows "CotD.exe has stopped working":
void load(vector<Fish>& stock)
{
char c;
do {
cout << "Welcome to Catch of The Day, enter (f) to choose a file to load from, otherwise enter anything else to load from default file.\n";
cin >> c;
if (c == 'f' || c == 'F')
{
cout << "Enter file name\n";
cin >> file;
}
ifstream fin(file.c_str());
if (fin.fail())
{
cout << "Could not open " << file << " Check the directory location of CotD.exe and try again\n";
}
else
{
while (!fin.eof())
{
Fish f;
string blank;
fin >> f.amt;
fin >> f.prc;
fin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
getline(fin, blank);
stock.push_back(f);
}
fin.close();
break;
}
} while (true);
}
EDIT other relevant code:
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
using namespace std;
//
string file = "default.txt"; //Global variable used to store name of save file.
//It is global so that load() and save() can both access it.
struct Fish
{
string type;
double amt;
double prc;
double val;
};
void addType(vector<Fish>&);
void editStock(vector<Fish>&);
void sortBy(vector<Fish>&);
void sortAsc(vector<Fish>&,char);
void sortDesc(vector<Fish>&,char);
void display(vector<Fish>&);
int search(vector<Fish>&);
void save(vector<Fish>&);
void load(vector<Fish>&);
string getType();
int dispType(string,vector<Fish>&);
int find(string,vector<Fish>&);
double getAmt();
void delType(string,vector<Fish>&);
void menu(vector<Fish>&);
double getPrc();
int main(){
std::vector<Fish> stock;
load(stock);
menu(stock);
save(stock);
cout<<endl<<endl
<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
<<"|Thank you for using Catch of the Day|\n"
<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
system("Pause");
return 0;
}
I recently wrote this program which seems very similar to me, and ran perfectly I can't see the difference:
void load(vector<string>& names)
{
string file, name, bad;
while (true)
{
cout << "Input file name\n";
getline(cin, file);
ifstream fin(file.c_str());
if (fin.fail())
{
cout << "Could not open " << file << ", try again.\n";
}
else break;
}
ifstream fin(file.c_str());
while (!fin.eof())
{
fin >> bad;
fin >> name;
cout << "\"" << name << "\"" << endl;
}
system("Pause");
fin.close();
ifstream fin(file.c_str());
while (!fin.eof())
{
getline(fin, name);
names.push_back(name);
}
system("Pause");
fin.close();
cout << "Names added to list\n";
}
I've edited your code, this is what I got:
void load(vector<Fish>& stock)
{
char c;
do {
cout << "Welcome to Catch of The Day, enter (f) to choose a file to load from, otherwise enter anything else to load from default file.\n";
cin >> c;
if (c == 'f' || c == 'F')
{
cout << "Enter file name\n";
cin >> file;
}
ifstream fin(file.c_str());
if (fin.fail())
{
cout << "Could not open " << file << " Check the directory location of CotD.exe and try again\n";
}
else
{
Fish f;
string blank;
if (fin>>f.amt)
{
if (fin>>f.prc)
{
getline(fin,blank);
stock.pushback(f);
}
}
fin.close();
break;
}
} while (true);
}
Of course, this is without knowing what is in the file and what the heck Fish is, so I do not know if this is what you are looking for.
EDIT:If you could include the file, or just a section of one "fish" as I assume that is what the contents of the file are, it would be alot easier to help.

reading from a text file that contains numbers and characters

I recently learned how to read data from a text file, but I would like to continue expanding my knowledge on that matter. I would like to read files that contain numbers and characters. Can anyone give me some advice please?
The following is the code I wrote to read numbers:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream infile("input.txt", ios::in);
if (!infile) {
cout << "Inputxxxxx file could not be opened" << endl;
exit(1);
}
ofstream outfile ("outputt.txt", ios::out);
if (!outfile) {
cout << "inputssss file could not be opened " <<endl;
exit(1);
}
int number;
int answer[10];
for (int i = 0; i < 9 ; i++) {
infile >> number;
answer[i]=number;
cout << answer[i] << " ";
outfile <<answer[i]<< " ";
}
return 0;
}