
C++读取文件getline函数报错?
代码:#include<iostream>#include<fstream>#include<cstdlib>#include<string>usingnamespace...
代码:
#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&)'| 展开
#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个回答
2019-11-19 · 百度认证:云南新华电脑职业培训学校官方账号

云南新华电脑学校是经云南省教育厅批准成立的省(部)级重点计算机专业学校,采用三元化管理模式,教学设备先进,师资雄厚学生毕业即就业,学院引进了电商企业入驻,创建心为电商创业园区,实现在校即创业
向TA提问
关注

展开全部
方法/步骤
1
工程目录下创建文本文件resource\\test.txt, 并输入如下内容
请点击输入图片描述
2
工程主函数输入如下代码段,功能是从文本文件读取信息,并显示到窗口终端上
请点击输入图片描述
3
输入完成代码之后,运行的结果如下所示, 文本文件的信息都正常显示出来
请点击输入图片描述
4
文本文件再加入一行信息,其内容超过代码中acbuf定义的长度,运行之后程序直接卡死
请点击输入图片描述
5
这里提供两种解决办法,一种办法如下所示,ifs.getline调用good判断,如果异常直接退出
请点击输入图片描述
6
输入完成上面的代码段之后,程序运行的结果如下所示
请点击输入图片描述
7
另一种方法是扩大acbuf的大小,扩大之后,程序运行结果如下所示,所有信息都能够显示出来,但是这个方法的缺陷是当读取到的信息又大于数组的大小的时候,程序又会卡死。所以,最好的方法是将两种方法结合起来,既扩大缓存,又添加异常判断条件。
请点击输入图片描述
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询