C++读取文件getline函数报错?

代码:
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>

using namespace std;

struct Patrons
{
string name;
double money;
};

int main(void)
{
int number;
ofstream outfile;
outfile.open("TestData\\Patrons.txt");
cout<<"Please enter the number of patrons: ";
cin>>number;
outfile<<number<<endl;
Patrons *pat = new Patrons [number];
cout<<"Please enter patrons' name and money:"<<endl;
int key = 0;
while(key<number)
{
cout<<"name: ";
cin>>pat[key].name;
cout<<"money: ";
cin>>pat[key].money;
outfile<<pat[key].name<<endl;
outfile<<pat[key].money<<endl;
key++;
}
delete [] pat;
outfile.close();

ofstream infile;
infile.open("TestData\\Patrons.txt");
if(!infile.is_open())
{
cout<<"文件打开失败!";
exit(EXIT_FAILURE);
}
int num;
string Name;
double Money;
getline(infile,num);
while(infile.good())
{
getline(infile,Name);
getline(infile,Money);
cout<<"Name: "<<Name<<"\tMoney: "<<Money<< endl;
}
infile.close();

return 0;
}

报错:
Test\main.cpp|48|error: no matching function for call to 'getline(std::ofstream&, int&)'|

方法/步骤

    1

    工程目录下创建文本文件resource\\test.txt, 并输入如下内容

    请点击输入图片描述

    2

    工程主函数输入如下代码段,功能是从文本文件读取信息,并显示到窗口终端上

    请点击输入图片描述

    3

    输入完成代码之后,运行的结果如下所示, 文本文件的信息都正常显示出来

    请点击输入图片描述

    4

    文本文件再加入一行信息,其内容超过代码中acbuf定义的长度,运行之后程序直接卡死

    请点击输入图片描述

    5

    这里提供两种解决办法,一种办法如下所示,ifs.getline调用good判断,如果异常直接退出

    请点击输入图片描述

    6

    输入完成上面的代码段之后,程序运行的结果如下所示

    请点击输入图片描述

    7

    另一种方法是扩大acbuf的大小,扩大之后,程序运行结果如下所示,所有信息都能够显示出来,但是这个方法的缺陷是当读取到的信息又大于数组的大小的时候,程序又会卡死。所以,最好的方法是将两种方法结合起来,既扩大缓存,又添加异常判断条件。

    请点击输入图片描述

温馨提示:答案为网友推荐,仅供参考
相似回答