文件数据处理

一、文件的读写
(1)输入输出重定向
命令行格式:c:>programoutputfile
即运行名为program。exe的可执行程序,用文件inputfile作为输入,用文件outputfile作为输出。
例如:
c:>addnumbers <number.txt >output.txt
从文件number.txt中读取数据,运行结果写入到output.txt中。
(2)标准库文件流
头文件:
ifstream类:istream的派生类,用来读入文件。
ofstream类:ostream的派生类,用来写入文件。
fstream类:iostream的派生类,用来输入输出(读写)。
使用例题:

#include<fstream>
using namespace std;
int main()
{
ifstream in("number.txt");
int number,sum=0;
in>>number;
while(number!=0)
{
sum+=number;
in>>number;
}
in.close();
ofstream out;
out.open("output.txt");//也可使用ofstream out("output.txt");一步完成
out<<"sum is:"<<sum<<endl;
out.close();
}

(3)字符串流
头文件:
istringstream:istream的派生类,用来从string对象中读取数据。
ostringstream:ostream的派生类,用来向string对象写入格式化的内容。
stringstream:iostream的派生类,即可以读取,又可以写入。
strm.str(),返回字符串流strm中保存的字符串的副本。
strm.str(s),将字符串s复制到字符串流strm中,返回void。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值