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;
}
T 87 89 65 37 98
输出文件testSetout.txt中的内容:
student ID:T
Test Scores:8779653798
average score:75
问题:(1)假如改变testSet.txt中第一个为djy,输出中也只有d一个字符,如何全部提取?
(2)是不是定义变量的数量一定要等于文件中数据的数量?

被折叠的 条评论
为什么被折叠?



