4.5

本文介绍了一个使用C++实现的文件读取函数,该函数能够将文件内容逐行读入string类型的vector容器中,并展示了如何处理输入流直至文件结束。此外,还提供了一个读取流并进行错误处理的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
*编写一个函数,其唯一的形参和返回值都是istream&类型。
*该函数应一直读取流直到到达文件结束符为止
*还应该将读到的内容输出到标准输出中,
*最后,重设流使其有效,并返回流值。
*以cin为实参来调用测试函数
*/
#include "get.hpp"
#include <iostream>
using namespace std;

int main()
{
double dval;
get(cin);
cin >> dval;
cout << dval << endl;
return 0;
}


#ifndef GET
#define GET
#include <iostream>

std::istream& get(std::istream& in)
{
int ival;

while (in >>ival, !in.eof())
{
if (in.bad())
throw std::runtime_error ("IO stream corrupted");
if (in.fail())
{
std::cerr << "bad data, try again";
in.clear();
in.ignore(200,' ');
continue;
}
std::cout << ival << " ";
}
in.clear();
return in;

}
#endif

/*
*编写函数打开文件用于输入,、
*将文件内容读入string类型的vector容器,
*每一行存储为该容器对象的一个元素
*/

#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

int main()
{
ifstream ifcin;
vector<string> ivec;
string str;

ifcin.open ("D:\\wer.txt");//在D盘下新建wer.txt,并输入字符。

if(!ifcin)
{
cerr << "open fail" << endl;
return -1;
}
while( !ifcin.eof ())
{
getline(ifcin,str);
ivec.push_back(str);
}

ifcin.close();

for(vector<string>::iterator iter = ivec.begin();iter != ivec.end();++iter)
{
cout << *iter <<endl;
}


system("pause");
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值