0

MY CODE ONLY PRINTS OUT 1 OBJECT INSTEAD OF ALL OF THEM. I’m suppose to use the overloaded extraction operator >> to extract Address objects one by one from a file named Address.dat.

Address.dat contains:

Hope St

67

Clarence

0917

Nelson Mandela Drive

643

Pretoria

0181

Albert St

91

Pretoria

0181

Church St

14

Wellington

6734

Main St

907

Soweto

0912

Bushbuck St

89

Polokwane

3452

As for my code is as follows:

#include <iostream>
#include <fstream>

using namespace std;

class Address{
   public:
     Address();
     void setStreetName(string strName);
     string getStreetName();
     void setStreetNr(int strNr);
     int getStreetNr();
     void setCity(string City);
     string getCity();
     void setPostalCode(string postalCd);
     string getPostalCode();
     friend istream &operator>>( istream  &input, Address &A );
     friend ostream &operator<<( ostream &output, const Address &B 
);

  private:
    string streetName;
    int streetNr;
    string city;
    string postalCode;
};

int main(){

//Reading data from Address.dat to object
ifstream file;
file.open("Address.dat");
Address Emp_1;
while(file){
  file >> Emp_1;
  cout << Emp_1 << endl;
}
file2.close();

return 0;
 }

Address::Address(){
streetName = "";
streetNr = 0;
city = "";
postalCode = "0000";
}

void Address::setStreetName(string strName){
streetName = strName;
}

string Address::getStreetName(){
return streetName;
}

void Address::setStreetNr(int strNr){
streetNr = strNr;
}

int Address::getStreetNr(){
return streetNr;
}

void Address::setCity(string City){
city = City;
}

string Address::getCity(){
return city;
}

void Address::setPostalCode(string postalCd){
postalCode = postalCd;
}

string Address::getPostalCode(){
return postalCode;
}

istream &operator>>( istream  &input, Address &A ){
getline(input,A.streetName);
input >> A.streetNr >> A.city >> A.postalCode;
return input;
}

ostream &operator<<( ostream &output, const Address &B ){
output << B.streetName << '\n' << B.streetNr << '\n' <<
          B.city << '\n' << B.postalCode << '\n';
return output;
}

Please assist in any way possible.BTW While(!file.eof()) gives an infinite loop...

Karen Baghdasaryan
  • 2,407
  • 6
  • 24
  • Think carefully about how your extraction operator handles the newlines in your data. That's where the error is. Since your input is split into lines I would use `getline` to read everything (even the street number). That's the simplest way to get it to work. – john Jul 27 '22 at 18:59
  • You are attempting to repeatedly read input both with `std::getline` and `>>`. This always ends in a spectacular failure. – Sam Varshavchik Jul 27 '22 at 19:39

0 Answers0