文件操作

  1. // 我们只需要学会两个语句即可
  2. // 输入输出文件,和.cpp放在同一个文件夹里即可
  3. // 实际操作中,复赛会要求文件输入输出
  4. // 注意输入输出文件的命名规范
  5. // 测试的时候,一般还会用标准输入输出测试
  6. // 最后还是要用文件输入输入测一下,然后把输入输出文件的名称写对
  7. // 最后的最后,检查文件夹命名、.cpp命名、输入输出文件命名
  8. #include <stdio.h>
  9. freopen("1.in", "r", stdin);
  10. freopen("1.out", "w", stdout);

结构体 struct

在实际问题中,一组数据往往有不同的数据类型,比如学生,有姓名、学号、语文成绩、数学成绩等等。C++语言给出了一种构造数据类型—“结构体”,结构体在数据存储方面相当于其他高级语言中的记录,但它悠着面向对象的优势。

  1. struct stu{
  2. string name;
  3. int id;
  4. int chinese, math;
  5. };

结构体的构造函数

https://blog.csdn.net/a_forever_dream/article/details/88867801

  1. // struct构造函数,说白了,就是初始化
  2. struct stu{
  3. string name;
  4. int id;
  5. int chinese, math;
  6. stu(){}
  7. stu(string a, int b, int c, int d){
  8. name = a, id = b, chinese = c, math = d;
  9. }
  10. };
  1. // 构造函数,具体展开讲解
  2. struct node(){
  3. int x, y;
  4. node(){}
  5. node(int c){
  6. x = 0, y = c; // 这种写法严格是赋值,不是初始化
  7. }
  8. node(int c):x(0), y(c){} // 这种写法是初始化, 象征性的大括号不能丢
  9. };
  1. // 举例,看看输出什么
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. struct node{
  5. int x;
  6. node():x(1){}
  7. };
  8. int main(){
  9. node a;
  10. cout << a.x << '\n';
  11. return 0;
  12. }
  13. // 输出 1
  1. // 一个结构体,可以有多个构造函数,要求每个构造函数的形参表不能一样
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. struct node{
  5. int x;
  6. node():x(1){}
  7. node(int a):x(a){}
  8. };
  9. int main(){
  10. node a, b(5);
  11. cout << a.x << ' '<< b.x << '\n';
  12. return 0;
  13. }
  14. // 输出 1 5
  1. // 给一个比较具有实战性质的示范代码
  2. // 下面的代码中,node a,这样初始化,当然是可以的
  3. // 但在node b(3, 4)的写法,非常简洁易读,在入队、入堆的操作中,非常省事
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6. struct node{
  7. int x, y;
  8. node(){}
  9. node(int a, int b): x(a), y(b){}
  10. };
  11. int main(){
  12. node a;
  13. a.x = 5, a.y = 6;
  14. node b(3, 4);
  15. printf("%d %d\n", a.x, a.y);
  16. printf("%d %d\n", b.x, b.y);
  17. return 0;
  18. }

文本文件类型与二进制文件类型

二进制文件是把内存中的数据按其在内存中的存储形式原样输出到磁盘上存放,也就是说存放的是数据的原形式。

文本文件是把数据的终端形式的二进制数据输出到磁盘上存放,也就是说存放的是数据的终端形式。