Xi'an Petroleum University C++ computer experiment computer six input and output flow program design

Computer six-input-output stream programming

1. The purpose of boarding

1. Understand the structure of the C++ stream class library.

2. Master the usage methods of commonly used classes and their member functions in the stream class library.

3. Understand the use of common control characters, and master the input and output methods of C++ format.

4. Proficiency in file operation methods and input and output of file streams.

2. On-board content

1. Test the examples in this chapter.

2. Design a student class, write the basic information (name, height, age) of N student objects into a file in the form of a binary stream, and randomly display the written file information on the screen

test example

[Example 9.9] Random access to files. Requirements:
(1) Design a student structure including name, student ID and grades.
(2) Write the data of 3 students into the file bbb.dat first, then read the data of the second student from the file
and display it on the screen.
Steps on the computer:
(1) Create a new plural class template header file. Select the menu "File" - "New" to open the new dialog box,
as shown in Figure 5-1. Select "C/C++ Header File" in the "Files" tab, set the storage path to
"D:\mywork\work6", and the file name to "Student". By default, "Add to project" is selected, as
shown in Figure 6-4.

2)单击“OK”按钮,打开 Student.h 文件,编辑代码如下:
//Student.h
struct Student{
    
    
char name[20];
long number;
int score;
};3)在主文件中 work6.cpp 中编辑测试代码:
#include "Student.h"
#include <fstream.h>
int main(int argc, char* argv[])
{
    
    
Student stu[3] = {
    
    {
    
    "Zhang", 111, 100}, {
    
    "Li", 222, 90}, {
    
    "Wang", 333, 80}}, 
stu2;
char filename[] = "bbb.data";
int n=3, i;
fstream datafile(filename, ios::in|ios::out|ios::binary);
for(i=0; i<3; i++)
datafile.write((char*)&stu[i], sizeof(struct Student));
datafile.seekg(1*sizeof(struct Student), ios::beg);
datafile.read((char*)&stu2, sizeof(struct Student));
datafile.close();
64
cout<<"Name: "<<stu2.name<<endl;
cout<<"Number: "<<stu2.number<<endl;
cout<<"score: "<<stu2.score<<endl;
return 0;
}

(4) Click the "Build" command icon in the toolbar to generate work6.exe.
(5) Click the "Excute" command icon in the toolbar to run work6.exe,

  1. Hands-on practice
    Design a student class, write the basic information (name, height, age) of N student objects into a file in the form of a binary stream, and randomly display the written file information on the screen.

On-board steps:

(1) Create a new plural class template header file. Select the menu "File" - "New" to open the new dialog box, as shown in Figure 6-6. Select "C/C++ Header File" in the "Files" tab, set the storage path to "D:\mywork\work6", and the file name to "Student2". By default, "Add to project" is selected, as shown in Figure 6-6 .Figure
6-6 Create a new student class header file

2)单击“OK”按钮,打开 Student2.h 文件,编辑代码如下:
//Student2.h
#include <string.h>
class Student{
    
    
public:
char name[20];
float height;
int age;
Student(char *n=" ", float h=1.6, int a=20) : height(h), age(a)
{
    
    
strcpy(name, n);
}
};3)在主文件中 work6.cpp 中编辑测试代码:

#include "stdafx.h"
#include "Student2.h"
#include <fstream.h>
int main(int argc, char* argv[])
{
    
    
int n;
cout<<"please input the number of student: ";
cin>>n;
66
Student *ps, stu;
ps = new Student[n];
char name[20];
float height;
int age;
for(int i=0; i<n; i++)
{
    
    
cout<<endl<<"Name: "; cin>>name; 
cout<<"Height: "; cin>>height;
cout<<"Age: "; cin>>age; 
*(ps+i) = Student(name, height, age);
}
char filename[] = "info.data";
fstream datafile(filename, ios::in|ios::out|ios::binary);
for(i=0; i<n; i++)
datafile.write((char*)(ps+i), sizeof(struct Student));
int num;
cout<<"Please input the number to print: ";
cin>>num;
while(num)
{
    
    
datafile.seekg((num-1)*sizeof(struct Student), ios::beg);
datafile.read((char*)&stu, sizeof(struct Student));
cout<<"Name: "<<stu.name<<endl;
cout<<"Height: "<<stu.height<<endl;
cout<<"Age: "<<stu.age<<endl;
cout<<"Please input the number to print: ";
cin>>num;
}
datafile.close();
return 0;
}

(4) Click the "Build" command icon in the toolbar to generate work6.exe.
(5) Click the "Excute" command icon in the toolbar to run work6.exe

thinking questions

1. In C++, random access to files is realized by controlling the movement of file pointers. Generally, text files are difficult to locate accurately, so random access is mostly used for binary files. Please test. What factors need to be considered when implementing random access to files in C++?

Implementing random access to files in C++ requires consideration of the following factors:

  1. When opening a file, you need to specify the correct file access mode and open method. For binary files, the "binary" mode should be used for read and write operations to avoid accidental changes to the data.

  2. The movement of the file pointer position. Random access can be achieved by calling the fseek function to move the file pointer to the desired location. When moving the pointer, you need to pay attention to the unit of the offset and the positive and negative directions to ensure that the file pointer moves to the correct position.

  3. The size and format of the data read or written. For binary files, since the size and format of the data types may vary, the data size and format to be read or written need to be determined on a case-by-case basis.

  4. When closing a file, it is necessary to ensure that all file pointers are correctly pointing to the end of the file to avoid data loss and corruption.

Here is a simple example showing how to randomly access a binary file in C++:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    // 打开二进制文件
    fstream file("test.bin", ios::out | ios::binary);

    // 写入数据
    int num1 = 12345;
    float num2 = 3.1415926;
    file.write(reinterpret_cast<char*>(&num1), sizeof(num1));
    file.write(reinterpret_cast<char*>(&num2), sizeof(num2));

    // 将文件指针移动到开头
    file.seekg(0);

    // 读取数据
    int num3;
    float num4;
    file.read(reinterpret_cast<char*>(&num3), sizeof(num3));
    file.read(reinterpret_cast<char*>(&num4), sizeof(num4));

    // 输出数据
    cout << "num1 = " << num3 << endl;
    cout << "num2 = " << num4 << endl;

    // 关闭文件
    file.close();
    
    return 0;
}

In the example above, we first opened a binary file called "test.bin" and wrote an integer and a float to it. Then, the file pointer is moved to the beginning of the file by calling the seekg function, and then the two data are read and output. Finally closed the file.

2. Test the difference between seekp function and seekg function to realize file pointer relocation?
In C++, there are two types of file pointers: read pointers and write pointers. For the convenience of operation, the C++ standard library provides the seekg and seekp functions to realize the relocation of the two pointer positions.

The seekg function is a function used to change the position of the current file read pointer, which allows the file read pointer to be positioned at any position in the file, thereby realizing random access when reading data. The seekp function is a function used to change the position of the current file write pointer, which allows the file write pointer to be positioned at any position in the file, thereby realizing random access when inserting and modifying data.

The following is a simple example that demonstrates how to use the seekg and seekp functions to implement file pointer relocation:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    // 打开文件
    fstream file("test.txt", ios::out | ios::in);

    // 写入数据
    file << "0123456789";

    // 重定位读指针(从开头开始向右移动3个字符)
    file.seekg(3, ios::beg);

    // 读取一个字符
    char ch;
    file.get(ch);
    cout << ch << endl;   // 输出3

    // 重定位写指针(从当前位置开始向右移动2个字符)
    file.seekp(2, ios::cur);

    // 插入一个字符
    file.put('A');

    // 重定位读指针(从开头开始向右移动2个字符)
    file.seekg(2, ios::beg);

    // 读取一个字符
    file.get(ch);
    cout << ch << endl;   // 输出0

    // 关闭文件
    file.close();
    
    return 0;
}

In the example above, we first opened a file called "test.txt" and wrote a string of numbers into it. Then, the file read pointer is moved to the fourth character position of the string by calling the seekg function, and then this character is read and output. Next, we move the file write pointer to the last two characters of the current read pointer by calling the seekp function, and then insert a capital letter "A" into the file. Finally, we call the seekg function again to move the file read pointer to the third character position of the string, and then read this character again and output it.

It can be seen that by using seekg and seekp functions, we can flexibly control the position of the file pointer, thereby realizing flexible access and modification of file data. It should be noted that the calculation methods and meanings of the offset parameters of the two functions are slightly different, please select the appropriate parameter type and parameter value according to the specific situation.

3. Complement and improve the topic content of [Practice on the computer], sort the student information according to user needs (according to height, age) and then display the information of N students.

Guess you like

Origin blog.csdn.net/shaozheng0503/article/details/130645396