【问题标题】:C++ while(getline()) not working properlyC++ while(getline()) 无法正常工作
【发布时间】:2017-01-27 00:51:24
【问题描述】:

我正在使用 getline 开始从文件中读取信息。问题是它永远不会进入while循环,即使文件中有数据要读取。有谁看到问题可能是什么?我知道我的代码可能不是最好的格式,但现在我严格关注 while(getline())

void loadPatients(Doctor Doctor[], int size)
{
    std::ifstream patientFile;
    Patient** patientInfo;
    std::string Address, DoctorId, Id, Name, PhoneNumber,junk;
    int patientNumber;
    patientInfo = new Patient*[size];
    for (int b = 0; b < size; b++)
        patientInfo[b] = new Patient[10];

    for (int i = 0; i < size; i++)
    {
        DoctorId = Doctor[i].getId();
        patientFile.open(DoctorId);
        patientNumber = Doctor[i].getNumberOfPatient();
        for (int a = 0; a < patientNumber; a++)
        {
            while (getline(patientFile, Name))
            {
                getline(patientFile, Id);
                getline(patientFile, Address);
                getline(patientFile, PhoneNumber);
                getline(patientFile, DoctorId);
            }
            patientInfo[i][a].setAddress(Address);
            std::cout << Address;
            patientInfo[i][a].setName(Name);
            patientInfo[i][a].setDoctorId(DoctorId);
            patientInfo[i][a].setId(Id);
            patientInfo[i][a].setPhoneNumber(PhoneNumber);
        }
        patientFile.close();

    }

【问题讨论】:

  • 如果它永远不会到达 while 循环,那么检查 for 循环终止条件,所以检查 size 和 patientNumber...。使用 cout 语句,看看它没有进入的地方
  • 我已经这样做了,我可能应该提到,它到达了while循环之前的行,但没有进入它
  • 你可以试试 while(patientFile.good()) ,然后将 getline(patientFile,Name) 移动到 while 内,看看它是否进入循环
  • 啊好吧还是没进去,所以打开文件有问题
  • 是的,所以检查一下 DoctorId 是什么。

标签: c++ ifstream getline


【解决方案1】:

patientFile.open(DoctorId) 需要 .txt 扩展名.. 所以 patientFile.open(DoctorId+".txt")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-11
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    相关资源
    最近更新 更多