0

I have a problem with my program. It has trouble reading lines from a text file when there are more than 1 word as a string. Here is the description for what my program is supposed to do:

Create a data type that describes island (create class).

Island has – name, area and location.

Include all the necessary functions, in your opinion. Overload >> and << operators. Write a program that will create an array of N-element islands and write in it the information about the islands from island.txt file (the number of islands is not more than 12).

Find the island with the largest area and print its name and location.

The island.txt file:

New Britain 35,145 Papua New Guinea   
Taiwan (main island) 34,507 Republic of China (Taiwan)  
Prince of Wales Island  33,339 Canada (Nunavut)  
Yuzhny Island (Novaya Zemlya, south) 33,246 Russia (Arkhangelsk)  
Hainan  33,210 China (Hainan Province)  
Vancouver Island 31,285 Canada (British Columbia)  
Timor 28,418 Indonesia

The code:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

class Islands {
    string name;
    double area;
    string location;
public:
    void pop(istream& input) {
        input >> name >> area >> location;
    }
    string getName() {
        return name;
    }
    double getArea() {
        return area;
    }
    string getLocation() {
        return location;
    }
    void display(ostream& output) {
        output << name << " " << area << " " << location;
    }
};

istream& operator>>(istream& in, Islands& island) {
    island.pop(in);
    return in;
}

bool compareArea(Islands& l1, Islands& l2) {
    return l1.getArea() > l2.getArea();
}

ostream& operator<<(ostream& out, Islands& island) {
    island.display(out);
    return out;
}

int main() {
    Islands l1;
    ifstream fin("island.txt");
    vector<Islands> island;
    while (!fin.eof()) {
        fin >> l1;
        island.push_back(l1);
    }
    cout << "List of Islands: " << endl;
    for (auto Islands : island) {
        cout << Islands;
    }
    sort(island.begin(), island.end(), compareArea);
    
    return 0;
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
Jhinius
  • 1
  • 1
  • 3
    You probably want to read a line at a time into a std::string and parse that string. – drescherjm May 11 '21 at 16:14
  • 3
    That is done with [`std::getline()`](https://en.cppreference.com/w/cpp/string/basic_string/getline). – sweenish May 11 '21 at 16:22
  • 1
    On a side note: [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/) `while (!fin.eof()) { fin >> l1; ... }` should be `while (fin >> l1) { ... }` – Remy Lebeau May 11 '21 at 16:49
  • See also: `std::istringstream`. – Thomas Matthews May 11 '21 at 16:51

0 Answers0