Need help reading in multiple strings from file
May 6, 2013 at 12:21am UTC
I have a class composed of three string type data members. I need two functions that will read and write that data directly from that class to file. The output function works just fine. I used it with test data earlier. It's the input function I'm having issues with. Gives me the following syntax errors:
mjccourse.cpp: In function ‘std::ifstream& operator>>(std::ifstream&, const MJCCourse&)’:
mjccourse.cpp:47: error: no match for ‘operator>>’ in ‘lhs >> rhs->MJCCourse::dept’
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
// mjccourse.h
#ifndef MJCCOURSE_H
#define MJCCOURSE_H
#include <iostream>
#include <fstream>
class MJCCourse
{
private :
std::string dept;
std::string ccode;
std::string scode;
public :
MJCCourse();
~MJCCourse();
friend std::ifstream& operator >>(std::ifstream&, const MJCCourse&);
friend std::ofstream& operator <<(std::ofstream&, const MJCCourse&);
};
#endif
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
// mjccourse.cpp
#include "mjccourse.h"
// default ctor with member initialization
MJCCourse::MJCCourse()
: dept("I need " ), ccode("some " ), scode("code!" )
{
}
// destructor
MJCCourse::~MJCCourse()
{
dept = ccode = scode = "" ;
}
// read a MJCCourse from file
std::ifstream& operator >>(std::ifstream &lhs, const MJCCourse &rhs)
{
lhs >> rhs.dept >> rhs.ccode >> rhs.scode;
return lhs;
}
// write a MJCCourse to file
std::ofstream& operator <<(std::ofstream &lhs, const MJCCourse &rhs)
{
lhs << rhs.dept << rhs.ccode << rhs.scode << std::endl;
return lhs;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
// mjcc1main.cpp
#include <cstdlib> // for exit()
#include "mjccourse.h"
int main()
{
std::ifstream infile;
std::ofstream outfile;
infile.open("cour2331.txt" );
if (!infile.good())
{
std::cerr << "Unable to open cour2331.txt file for reading!" << std::endl;
exit(1);
}
outfile.open("mjcclist.txt" );
if (!outfile.good())
{
std::cerr << "Unable to open mjcclist.txt file for editing!" << std::endl;
exit(2);
}
MJCCourse t1;
infile >> t1;
outfile << t1;
infile.close();
outfile.close();
return 0;
}
First five lines from input file. Also, I'm just trying to read in one line in main for now, until I know what I'm doing.
1 2 3 4 5
MATH 1347 001
ITSE 1331 001
ENGL 1383 001
ITSW 1391 001
LATN 0357 001
May 6, 2013 at 5:28pm UTC
Nevermind. I was passing by a constant reference in my '>>' function. Should have been this way:
std::ifstream& operator >>(std::ifstream &lhs, const MJCCourse &rhs)
Topic archived. No new replies allowed.