Find the error(s) and show how to correct it(them) in each of the following.
a.
File
pets.dat
that stores its id, name, age and owner
of the pet is referred to by ofstream object
petfile
.
petfile>>pet_id>>pet_name>>pet_age>>pet_owner;
b.
The following statement should create an ifstream object
salesfile
that refers to the file
weeklysales.dat
that contains data about the id the
salesperson, total sales generated, and the
week number, read the data from the file and display it on the console output.
ifstream salesfile(“weeklysales.dat”);
int id,wk;
float sales;
salesfile>>id>>wk>>sales;
while (!salesfile.eof()){
cout<<id<<”\t”<<sales<<”\t”<<wk<<”\n”;
salesfile<<id<<wk<<sales;
}
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Use "" instead of “”. “” are not valid
ifstream salesfile("weeklysales.dat");
int id,wk;
float sales;
while (!salesfile.eof()){
// Next line should be inside while loop. Because you want to read every line, not first line n times, i guess.
salesfile>>id>>wk>>sales;
// Same here. Use "" instead of “”.
cout<<id<<"\t"<<sales<<"\t"<<wk<<"\n";
// Why did you put the following line here? You can't write to a istream and you don't have to return your data to a file after use. Next line is useless.
//salesfile<<id<<wk<<sales;
}
}
Comments
Leave a comment