0

My code is not working as expected. When I run the program and try to output n ( on line ABC ) , the program displays only "New" on the screen. why isn't the program reading the rest of the file? Any help will be appreciated. Thanks

#include <iostream>
#include <fstream>
using namespace std;

class stateData{
private:
    string name, capital;
    int area, admissionYear, admissonOrder;
public:
friend ifstream& operator>>(ifstream& input, stateData &state);
friend ostream& operator<<(ofstream& output, stateData &state);

};


ifstream& operator >>(ifstream &input, stateData &state){
    string name, capital,n;
    int area, admissionYear, admissionOrder;
    input >> n;
    input>>capital;
    input>>area;
    input>>admissionYear;
    input>>admissionOrder;
    state.name=n;
    cout << n;  // LINE ABC
}


int main(){
    stateData states[50];
    string n;
    ifstream infile;
    ofstream outfile;
    int hashTable[101];
    infile.open("Ch9_Ex8_data.txt");
    if (infile.fail()){
        cout << "Sorry, file could not be opened. ";
        exit(0);
    }
    for (int i=0; i<50; i++){
        infile>> states[i];
    }
}
}

Given below is the contents of the file: "

New Hampshire 
Concord
9304 1788 9
Massachusetts
Boston
8257 1788 6

...

Anon 123
  • 73
  • 5
  • @cigien thanks for spotting the mistake. changed it, but to no effect. still only displays "new" – Anon 123 Jun 15 '20 at 01:12
  • 2
    [Read file line by line using ifstream in C++ - Stack Overflow](https://stackoverflow.com/questions/7868936/read-file-line-by-line-using-ifstream-in-c) – user202729 Jun 15 '20 at 01:13
  • @user202729 im still reading the file line by line, even though it may not be till the end of the file. input>> n first reads a line and the next time the statement is executed, even the next line read automatically? – Anon 123 Jun 15 '20 at 01:19
  • No it doesn't. Read the linked question carefully. – user202729 Jun 15 '20 at 01:20
  • FYI: [operator>>(std::string)](https://en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt) One of the reasons to stop input is the occurrence of a whitespace: _`std::isspace(c,is.getloc())` is true for the next character c in is (this whitespace character remains in the input stream)._ Hence `input >> n;` reads `New` but leaves ` Hampshire` in the input buffer. – Scheff's Cat Jun 15 '20 at 05:51

0 Answers0