C++-文件输入输出流-学生信息读取/文件复制

题目1.

从键盘输入若干学生信息,写入文本文件中,再从该文本文件中读出学生的信息。

具体要求如下:

(1)应定义学生类Student,成员数据包括学号、姓名和成绩等;

(2)建议用友元函数为学生类重载输入输出流的<<和>>运算符,实现学生信息的整体输入输出功能;例如:

    friend istream& operator >> (istream&, Student&);

friend ostream& operator << (ostream&, Student&);

(3) 要求在主函数中,从键盘输入多个学生的信息 

(4) 要求将全部学生信息存入文本文件中;

(5) 最后从文件中读出全部学生信息显示到屏幕上,并求平均成绩。

 

源代码(包括类和测试程序):

#include <iostream>
#include <cmath>
#include <cstring>
#include <fstream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <cstdlib>
#include <stdio.h>
using namespace std;
#define LEN  sizeof(Student)
#define filename "/Users/apple/Desktop/实验课/实验课/newfile.txt"
class Student
{
public:
    int score;
    string name;
    char number[5];
    friend istream& operator >> (istream&, Student&);
    friend ostream& operator << (ostream&, Student&);
    void input(Student&);
};
Student P[100];

istream& operator>> (istream &input , Student &P)
 {
     cout << "请输入要存储的学生信息:" <<endl;
     cout << "学号:";
     input >> P.number ;
     cout << "姓名:";
     input >> P.name ;
     cout << "分数:";
     input >>P.score ;
     return input;
 }

ostream& operator<< (ostream& output , Student &P)
 {
     output << "学号:" << P.number <<'\t' ;
     output << "姓名:" << P.name <<'\t';
     output << "成绩:" << P.score << endl;
     return output ;
 }
int main()
{
    Student p1 , p2 ,p3;
    cin >> p1 >> p2 >>p3 ;
    ofstream ofile; //打开文件
    if(!ofile)
    {cout << "Can not open the file." << endl ;}
    ofile.open(filename,ios::out);
    ofile << p1 <<endl;
    ofile << p2 <<endl;
    ofile << p3 <<endl;
    ofile.close();
    ifstream in(filename) ;
    if (!in) {
        cout << "Can not open file." ;
    }
    cout<<"全部学生信息如下:"<<endl;
    char ch;
    while (  in.get(ch) )  cout<<ch;
    cout<<"平均成绩:"<<(p1.score+p2.score+p3.score)/3<<endl;

}

讨论:(可在此讨论本题中遇到的问题和解决思路)

  1. 类中如果将数据放在private中,main函数里不好进行访问,遂移至public
  2. 将txt文件中的数据读取的部分不够完善(已修改)
  3. txt中第一行输出格式与其它行不一(未解决)
  4. outfileb报错  ofile才可以
  5. mac下直接创建的是rtf文件 rtf文件无法直接导入xcode 因此需要将rtf转换为txt
  6. Xcode导入txt文件步骤:右键Product->show in finder

题目2.

提示:应使用追加方式ios::app打开需要增加内容的文件。

#include <iostream>
#include <fstream>
using namespace std;

int main ( )
{
    ifstream  f1 ( "/Users/apple/Desktop/实验课/实验课/file1.txt" ) ;
    if  ( !f1 )
    { cout << "cannot open 'test' for input." ;}
    ofstream  f2 ( "/Users/apple/Desktop/实验课/实验课/file2.txt",ios::app ) ;
    if  ( !f2 )
    { cout << "cannot open testnew for ouput." ;   }
    char  ch ;
    while (  f1.get(ch) )   f2.put( ch ) ;
    f1.close () ;   f2.close () ;
    cout << "It is over !\n" ;
}

讨论:(可在此讨论本题中遇到的问题和解决思路)

1.不使用ios::app也能够运行?

猜你喜欢

转载自blog.csdn.net/loglian/article/details/106958960