【问题标题】:C++ program hangs when using cin.getline()使用 cin.getline() 时 C++ 程序挂起
【发布时间】:2016-03-02 14:34:15
【问题描述】:

我正在制作一个程序来跟踪不同的人,我尝试从文件中读取。我使用了一个将 ifstream 文件作为参数的构造函数,然后我尝试从文件中读取数据。我可以阅读第一行,这只是一个 int(每个人的唯一编号),但是当我尝试转到下一行并获取它时,程序挂起。有谁知道为什么?

#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
安迪
180885
2
迈克尔
230399

【问题讨论】:

    标签: c++ getline freeze


    【解决方案1】:

    在你的构造函数中

    cin.getline(fnavn, MAXTXT);
    

    所以你的程序正在等待你输入一些东西。如果你想从文件中获取名称,那么你需要

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

    您还会遇到mixing &gt;&gt; with getline 的问题。您将需要添加

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

    在你的while循环中infile &gt;&gt; nr;之后。

    【讨论】:

    • 但是现在它把名字放在了生日字段中。怎么来的?来自文件内容的这种输入让我大吃一惊。
    • @AndreasBH 我补充了为什么会这样。您应该阅读随附的链接以获取详细说明。
    【解决方案2】:

    strlen(fname + 1) 将是 strlen(fname) - 1 如果 fname 是一个字符或更多,并且如果 fname 是零字符长则不确定。应该是strlen(fname) + 1

    strlen(fnavn + 1) 有同样的问题,应该是strlen(fnavn) + 1

    【讨论】:

    • 我尝试将其更改为 strlen(fname) +1,但它仍然挂起。有什么线索吗?
    猜你喜欢
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多