文件的读写-简单数据处理

iostream头文件只用于从标准输入设备输入数据和向标准输入数据输出数据。

C++提供了一个用于文件I/O的、称为fstream的头文件。

fstream头文件包含两个数据类型的定义:ifstream,代表输入文件流,与istream类似;和ofstream,代表输出文件流,与ostream类似。

文件I/O分五步:

(1)在程序中包含头文件fstream。

(2)声明文件流变量。

(3)将文件流变量与<<、>>以及其他输入/输出函数一起使用。

(5)关闭文件。

示例如下:


#include<fstream>

#include<iostream>

using namespace std;

int main()
{
	ifstream infile;
	ofstream otfile;

	int test1, test2, test3, test4, test5;
	double average;
	char studentID;

	infile.open("C:\\Ccode\\Project2\\testSet.txt");
	otfile.open("C:\\Ccode\\Project2\\testSetout.txt");

	cout << "Processing data" << endl;
	infile >> studentID;
	otfile << "student ID:" << studentID << endl;

	infile >> test1 >> test2 >> test3  >> test4>> test5;
	otfile << "test scores:" << test1 << test2 << test3 << test4 << test5 << endl;

	average = (test1 + test2 + test3 + test4+test5) / 5;
	otfile << "average score:" << average << endl;

	infile.close();
	otfile.close();
	return 0;
	
}


文件testSet.txt中的内容:

T 87 89 65 37 98

输出文件testSetout.txt中的内容:

student ID:T

Test Scores:8779653798

average score:75

问题:(1)假如改变testSet.txt中第一个为djy,输出中也只有d一个字符,如何全部提取?

(2)是不是定义变量的数量一定要等于文件中数据的数量?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值