1、文件操作

一、从文件中读取数据ifstream>>
这里写图片描述

//功能:把文件中的数据读到变量的值中
#include<fstream> 
#include <string>
#include <iostream>
using namespace std;

int main()
{
    int i=0;
    int count = 0; //文件中
    string m_name , m_passwd;
    ifstream file_read;  //定义读取文件的对象
    file_read.open("name.txt");  //打开存放用户名和密码的文件
    if(!file_read)
    {
        cout<<"打开文件失败"<<endl;
    }
    else
    {
        while(!file_read.eof()) //用此方法会多循环一次
        {
            file_read>>m_name>>m_passwd;  //一行一行
            cout<<m_name<<"  "<<m_passwd<<endl;
            i++;
        }
        count = i;  //因为多循环一次,所以i的初始值是0
        file_read.close();
    }
}

二、往文件中写入数据ofstream<<

//功能:把变量的值写入到文件中
//将数组m_name、m_passwd、sex中的数据写入文件中
#include<fstream> 
#include <string>
#include <iostream>
using namespace std;
int main()
{
    int i=0;
    int count = 5; //文件中
    string m_name[5] = {"AA","BB","CC","DD","EE"};
    string m_passwd[5] = {"1","2","3","4","5"};
    string sex[5] = {"M","M","W","W","M"};

    ofstream file_write;
    file_write.open("name.txt");
    if(!file_write)
    {
        cout<<"打开文件失败"<<endl;
    }
    for(i=0;i<count;i++) //注意:空格、endl都可以写入文件中去
        file_write<<m_name[i]<<"  "<<m_passwd[i]<<"  "<<sex[i]<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值