-4

I am making a program keeping track of different persons, which I try to read in from a file. I use a constructor that takes an ifstream file as an argument, and I then try to read in the data from the file. I can read the first line, which is just an int (a unique number for each person), but when I try to go to the next line and getline it, the program hangs. Does anyone know why?

#include  <iostream>
#include  <fstream> 
#include  <cstring> 
#include  <cctype>  
#include  <cstdlib>
using namespace std;

const int MAXPERS = 100;
const int MAXTXT = 80;
const int DATELEN = 7;

class Person {
    private:
        int   nr;
        char* firstName;
        char  birthDate[DATELEN];

    public:
        Person() {
            char fname[MAXTXT];
            cout << "First name: "; cin.getline(fname, MAXTXT);
            firstName = new char[strlen(fname) + 1];
            strcpy(firstName, fname);
            cout << "Birth date (DDMMYY): ";
            cin >> birthDate; cin.ignore();
            }

        Person(int n, ifstream & in) {
            nr = n;
            char fname[MAXTXT];
            cin.getline(fname, MAXTXT);
            firstName = new char[strlen(fname) + 1];
            strcpy(firstName, fname);
            in >> birthDate;
            }

        void display() {
            cout << "\nFirst name: " << firstName;
            cout << "\nBorn: " << birthDate;
            }

        void writeToFile(ofstream & ut) {
            ut << firstName << "\n" << birthDate;
            }
        };

void readFromFile();

Person* persons[MAXPERS + 1];
int lastUsed = 0;

int main() {
    readFromFile();

    persons[1]->display();

    return 0;
    }

void readFromFile() {
    ifstream infile("ANSATTE.DAT");
    if(infile) {
        while(!infile.eof() && lastUsed < MAXPERS) {
            int nr;
            infile >> nr;
            persons[++lastUsed] = new Person(nr, infile);
            }
        }
    }

My file looks like this:

1
Andy
180885
2
Michael
230399

Andreas BH
  • 9
  • 2
  • 6

2 Answers2

1

In your constructor you have

cin.getline(fnavn, MAXTXT);

So your program is waiting for you to type something in. If you meant to get the name from the file then you need

in.getline(fnavn, MAXTXT);
^^ ifstream object

You are also going to run into the issue of mixing >> with getline. You will need to add

infile.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

after infile >> nr; in your while loop.

Community
  • 1
  • 1
NathanOliver
  • 150,499
  • 26
  • 240
  • 331
0

strlen(fname + 1) will be strlen(fname) - 1 if fname is one-character long or more and indeterminate if fname is zero-character long. It should be strlen(fname) + 1.

strlen(fnavn + 1) has the same issue and should be strlen(fnavn) + 1.

MikeCAT
  • 61,086
  • 10
  • 41
  • 58