简单文件输入/输出 C++(实验报告)(2)

[Experiment topic 2]

用编辑器(记事本等)产生一个文本文件data.txt,其内容为若干实数,数据之间以空白字符分割。编程从该文件中读入这些实数,求出这些实数的平均值,在程序中创建并产生一个文本文件result.txt,内容为data.txt中的全体实数,每行5个数,最后一行是求出的平均值。

 Experimental procedure

#include<iostream>
#include<fstream>	//file I/O support
#include<cstdlib>	//support for exit()
using namespace std;
const int SIZE = 60;
int main() {
	char filename[SIZE];
	ifstream inFile;	//object for handling file input
	cout << "Enter name of data file: ";
	cin.getline(filename, SIZE);
	inFile.open(filename);//associate inFile with a file
	if (!inFile.is_open())//failed to open file
	{
		cout << "Could not open the file " << filename << endl;
		cout << "Program terminating.\n";
		exit(EXIT_FAILURE);
	}
	double value;
	double sum = 0.0;
	int count = 0;//number of items read
	ofstream outFile;	//create object for output
	outFile.open("result.txt");
	inFile >> value;	//get first value
	while (inFile.good())//while input good and not at EOF
	{
		++count;//one more item read
		sum += value;//calculate running total
		outFile << value << " ";
		if (count%5==0)outFile << endl;	//每行5个数
		inFile >> value;//get next value
	}
	if (inFile.eof())
		cout << "End of file reached.\n";
	else if (inFile.fail())
		cout << "Input terminated by data mismatch.\n";
	else
		cout << "Input terminated for unknown reason.\n";
	if (count == 0)
		cout << "No data processed.\n";
	else {
		cout << "Items read: " << count << endl;
		cout << "Average: " << sum / count << endl;
		if (count % 5)outFile << endl;
		outFile << "Average: " << sum / count << endl;
	}
	inFile.close();	//finished with the file
	outFile.close();
	return 0;
}

 Experimental results and analysis

在这里插入图片描述
要运行程序,首先必须创建一个包含数字的文本文件。为此可用文本编辑器(如用于编写源代码的文本编辑器)假设该文件名为data.txt,包含的内容如下:
To run the program, you must first create a text file that contains numbers. For this purpose, you can use a text editor, such as one for writing source code, assuming that the file name is data.txt , including the following:
在这里插入图片描述
下面是程序运行后得到的文本文件result.txt,其中保存了从data.txt读取的值以及计算得出的平均值。
Here is the text file after the program runs result.txt , where the data.txt The value read and the calculated average.
在这里插入图片描述

 Experimental process analysis

程序中还必须能够找到这个文件。通常,除非在输入的文件名中包含路径,否则程序将在可执行文件所属的文件夹中查找。
警告:Windows文本文件的每行都以回车字符和换行符结尾;通常情况下,C++在读取文件时将这两个字符转换为换行符,并在写入文件时执行相反的转换。有些文本编辑器不会自动在最后一行末尾加上换行符。因此,如果读者使用的是这种编译器,请在输入最后的文本按下回车键,然后再保存文件。

This file must also be found in the program. In general, unless you include a path in the filename you enter, the program looks in the folder to which the executable belongs.
Warning: each line of a Windows text file ends with a carriage return character and a line feed character; typically, C + + converts these two characters to a line feed character when reading the file, and performs the opposite conversion when writing to the file. Some text editors do not automatically add line breaks at the end of the last line. So if you’re using this compiler, press enter at the end of the input text before saving the file.
如果试图打开一个不存在的文件用于输入,情况将如何呢?这种错误将导致后面使用ifstream对象进行输入时失败。检查文件是否被成功打开的首先方法是使用方法is_open(),为此,可以使用类似于下面的代码:
What happens if you try to open a non-existent file for input? This error will cause subsequent input failures using ifstream objects. The first way to check whether the file has been opened successfully is to use the method is_ Open (), to do this, you can use code similar to the following:

ifFilen.open(“bowling.txt”);
if ( !inFile.is_open() )
{
exit ( EXIT_FAILURE) ;
}

如果文件被成功打开,方法is_open()将返回true;因此如果文件没有被打开,表达式 !inFile.is_open()将为true。函数exit()的原型是在头文件cstdlib中定义的,在该头文件中,还定义了一个用于同操作系统通信的参数值EXIT_FAILURE。函数exit()终止程序。
If the file is opened successfully, method is_ Open() returns true; therefore, if the file is not opened, the expression! inFile.is_ Open() will be true. The prototype of the function exit() is defined in the header file cstdlib, which also defines a parameter value exit for communication with the operating system_ FAILURE。 The function exit() terminates the program.
该程序没有使用硬编码文件名,而是将用户提供的文件名存储到字符数组filename中,然后将该数组用作open()的参数:ifFile.open(filename);
检查文件是否被成功打开至关重要。下面是一些可能出现问题的地方:

Instead of using a hard coded filename, the program stores the filename provided by the user in the character array filename, which is then used as a parameter of open(): ifFile.open (filename);
It is critical to check that the file has been opened successfully. Here are some possible problems:
 指定的文件可能不存在;
 文件可能位于另一个目录(文件夹)中;
 访问可能被拒绝;
 用户可能输错了文件名或者省略了文件扩展名。

 The specified file may not exist;
 The file may be located in another directory (folder);
 Access may be denied;
 The user may have entered the wrong file name or omitted the file extension.
读取文件时,有几点需要检查。
 首先,程序读取文件时不应超过EOF。如果最后一次读取数据时遇到EOF,方法eof()将返回true。
 其次,程序可能遇到类型不匹配的情况。
例如,程序清单6.16期望文件中只包含数字。如果最后一次读取操作中发生了类型不匹配的情况,方法fail()将返回true(如果遇到EOF,该方法也将返回true)。
 最后,可能出现意外的问题,如文件受损或硬件故障。
如果最后一次读取文件时发生了这样的问题,方法bad()将返回true。不要分别检查这些情况,一种更简单的方法是使用good()方法,该方法在没有发生任何错误时返回true:

There are several points to check when reading a file.
Firstly, when the program reads the file, it should not exceed EOF. If EOF is encountered the last time data is read, method eof() returns true.
Secondly, the program may encounter type mismatch.
For example, listing 6.16 of the program expects only numbers in the file. If a type mismatch occurs during the last read operation, the method fail() returns true (and true if EOF is encountered).
Finally, unexpected problems may occur, such as file damage or hardware failure.
If this happens the last time a file is read, the method bad() returns true. Do not check these cases separately. A simpler way is to use the good () method, which returns true when no error occurs:
然后,如果愿意,可以使用其他方法来确定循环终止的真正原因:
Then, if you like, you can use other methods to determine the true cause of the loop termination:
在这里插入图片描述
方法good()指出最后一次读取输入的操作是否成功,这一点至关重要。这意味着应该装在执行读取输入的操作后,立刻应用这种测试。为此,一种标准方法是,在循环之前(首次执行循环测试前)放置一条输入语句,并在循环末尾(下次执行循环测试之前)放置另一条输入语句:
Method good () is critical to indicate whether the last operation to read the input was successful. This means that this test should be applied as soon as the read input operation is performed. To do this, a standard approach is to place an input statement before the loop (before the first loop test) and another input statement at the end of the loop (before the next loop test):
在这里插入图片描述
鉴于以下事实,可以对上述代码进行精简:表达式inFile>>value的结果为inFile,而在需要一个bool值的情况下,inFile的结果为inFile.good(),即true或false。因此,可以将两条输入语句用一条用作循环测试的输入语句代替。也就是说,可以将上述循环结构替换为如下循环结构:
In view of the following facts, the above code can be simplified: the result of the expression infile > > value is infile, while in the case of a bool value, the result of infile is inFile.good (), that is, true or false. Therefore, two input statements can be replaced by one as a loop test. In other words, the above-mentioned cycle structure can be replaced by the following cycle structure:
在这里插入图片描述

 Empirical conclusioin

重要的是,声明一个ifstream对象并将其同文件关联起来后,便可以像使用cin那样使用它。所有可用于cin的操作和方法都可用于ifstream对象
It is important to declare an ifstream object and associate it with a file so that you can use it as if you were using CIN. All operations and methods available for CIN are available for ifstream objects

Experiment summary

 文件输出

1. 必须包含头文件fstream。
2. 头文件fstream定义了一个用于处理输出的ofstream类。
3. 需要声明一个或多个ofstream变量(对象),并以自己喜欢的方式对其进行命名,条件是遵守常用的命名规则。
4. 必须指明名称空间std;例如,为引用元素ofstream,必须使用编译指令using或前缀std::。
5. 需要将ofstream对象与文件关联起来。为此,方法之一是使用open()方法。
6. 使用完文件后,应使用方法close()将其关闭。
7. 可结合使用ofstream对象和运算符<<来输出各种类型的数据。
8. 注意,虽然头文件iostream提供了一个预先定义好的名为cout的ostream对象,但您必须声明自己的ofstream对象,为其命名,并将其同文件关联起来。

  1. The header file fstream must be included.
  2. The header file fsstream defines an OFSTREAM class for processing output.
  3. You need to declare one or more OFSTREAM variables (objects) and name them in the way you like, provided that you abide by common naming rules.
  4. The namespace STD must be specified; for example, to reference the element OFSTREAM, you must use the compile instruction using or the prefix STD::.
  5. You need to associate OFSTREAM objects with files. One way to do this is to use the open () method.
  6. After using the file, use the method close() to close it.
  7. You can use OFSTREAM object and operator < < to output various types of data.
  8. Note that although the header file iostream provides a predefined ostream object named cout, you must declare your OFSTREAM object, name it, and associate it with the file.

文件输入

1. 必须包含头文件fstream。  头文件fstream定义了一个用于处理输入的ifstream类。
2. 需要声明一个或多个ifstream变量(对象),并以自己喜欢的方式对其进行命名,条件是遵守常用的命名规则。
3. 必须指明名称空间std;例如,为引用元素ifstream,必须使用编译指令using或前缀std::。
4. 需要将ifstream对象与文件关联起来。为此,方法之一是使用open()方法。  使用完文件后,应使用close()方法将其关闭。
5. 可结合使用ifstream对象和运算符>>来读取各种类型的数据。
6. 可以使用ifstream对象和get()方法来读取一个字符,使用ifstream对象和getline()来读取一行字符。
7. 可以结合使用ifstream和eof()、fali()等方法来判断输入是否成功。
8. ifstream对象本身被用作测试条件时,如果最后一个读取操作成功,它将被转换为布尔值true,否则被转换为false。

  1. The header file fstream must be included.
  2. The header file fsstream defines an OFSTREAM class for processing output.
  3. You need to declare one or more OFSTREAM variables (objects) and name them in the way you like, provided that you abide by common naming rules.
  4. The namespace STD must be specified; for example, to reference the element OFSTREAM, you must use the compile instruction using or the prefix STD::.
  5. You need to associate OFSTREAM objects with files. One way to do this is to use the open () method.
  6. After using the file, use the method close() to close it.
  7. You can use OFSTREAM object and operator < < to output various types of data.
  8. Note that although the header file iostream provides a predefined ostream object named cout, you must declare your OFSTREAM object, name it, and associate it with the file.

By Suki
2020.5.22
It’s a bad day.

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值