c++文本文件的输入和输出

c++对文件的操作使用数据流来实现的
对文件操作一般都是用里面的类来实现的
一般常用:
ifstream:对文件输入(读文件)
ofstream :对文件输出(写文件)
fstream : 对文件输入或输出

文件的输入:先用ifstream类定义一个对象
在用这个对象的方法打开文件,然后就可以把数据通过这个对象输入到文件中了(想象成一个管子,插到文件中,然后把数据流进去)最后不要忘记关闭文件。

#include<Windows.h>
#include<iostream>
#include<fstream>
using namespace std;
int main() {
 ifstream infile;
 infile.open("小猪猪.txt");
 string name;
 int age;
 while (1) {
  infile >> name;
  if (infile.eof()) {
   break;
  }
  cout << name << "\t";
  infile >> age;
  cout << age << endl;
 }
 infile.close();
 system("pause");
 return 0;
}

也可以用fstream 比如注释,但是用这个定义就系统就不知道你是干什么,所以需要指定操作
在这里插入图片描述
文件输出:方法与文件输入一样,不过就是用了ofstream类 ,并且因为通过空格来区分的,所以他会一个一个读取

#include<Windows.h>
#include<iostream>
#include<fstream>
using namespace std;
int main(){
 ofstream outfile;
 //fstream outfile;
 string name;
 int age;
 //outfile.open("小猪猪.txt", ios::out | ios::trunc );
 outfile.open("小猪猪.txt");
 while (1) {
  cout << "请输入姓名[输入ctrl+z结束]:";
  cin >> name;
  if (cin.eof()) {
   break;
  }
  cout << "请输入年龄:";
  cin >> age;
  outfile << name << "\t" << age << endl;
 }
 outfile.close();
 system("pause");
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值