我正在製作一個程序來跟蹤不同的人,我試圖從文件中讀入。我使用一個將ifstream文件作爲參數的構造函數,然後嘗試讀取文件中的數據。我可以閱讀第一行,這只是一個int(每個人都有一個唯一的編號),但是當我嘗試去下一行並對它進行getline時,程序就會掛起。有誰知道爲什麼?使用cin.getline()時C++程序掛起
#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);
}
}
}
我的文件是這樣的:
1 Andy 180885 2 Michael 230399
耶穌......謝謝! –
但現在它將名稱放在生日字段中。怎麼來的?來自文件的這種輸入令我感到不安。 –
@AndreasBH我補充了爲什麼發生這種情況。您應該閱讀附件鏈接以獲取詳細解釋。 – NathanOliver