欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++文件输入输出

程序员文章站 2024-03-18 18:02:34
...

首先是输入到文件中

ofstream outfile;
outfile.open(str);   /// str为对应文件的位置 例如 str = "D:\\outfile.dat";
outfile << ....       /// 输入相应的内容到文件中
outfile.close();     /// 关闭文件

接着是从文件中读取内容

ifstream infile;
infile.open(str);   /// str为对应文件的位置 例如 str = "D:\\outfile.dat";
infile >> ....       /// 从文件中读取内容
infile.close();		/// 关闭文件

实际的例子如下

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ofstream outfile("D:\\student.dat");
    string name,id;
    int math,eng,computer;
    for (int i = 0; i < 3; i++){
        cout << "输入姓名: ";   cin >> name;
        cout << "输入学号: ";   cin >> id;
        cout << "输入数学成绩: "; cin >> math;
        cout << "输入英语成绩: "; cin >> eng;
        cout << "输入计算机成绩: "; cin >> computer;
        outfile << name << " " << id << " " << math << " " << eng << " " << computer << endl;
    }
    outfile.close();
	
	system("pause");

    system("cls");

	ifstream infile("D:\\student.dat");
    string name,id;
    int math,eng,computer,sum = 0;
    cout << "姓名\t" << "学号\t" << "数学\t" << "英语\t" << "计算机\t" << "总分\t" << endl;
    infile >> name;
    while (!infile.eof()){
        infile >> id >> math >> eng >> computer;
        sum = math + eng + computer;
        cout << name << "\t" << id << "\t" << math << "\t" << eng << "\t" << computer << "\t" << sum << endl;
        infile >> name;
        sum = 0;
    }
    infile.close();
    return 0;
}

上一篇: java对各进制的转换

下一篇: