C/Cpp 杂记

文件操作

简单文件读写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<fstream>
using namespace std;

ifstream in;
in.open("file_path");
int k;
while(in >> k) // 读取 int 型数据
cout << k << endl;
in.close();

ofstream out;
out.open("out_path", ios::app); // app模式追加,默认覆写
out << ‘hello world’ << endl;
out.close();

编程规范

循环计数器与 ++ 运算符

考虑 while 和 do 计数循环:

1
2
3
4
5
6
7
8
i = 0;
while(++i < 1)
cout << "while: " << i << endl; // i 不会被打印

i = 0;
do{
cout << "do: " << i << endl; // i 被打印2次
}while(i++ < 1);

这里计数器 i 不能正常工作(打印一次),应该将计数器更新放在循环体避免失误,使用标准的 for 循环最好。

结构体声明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
struct struct_label{

}; // 结构标记声明
struct struct_label var_name; // 结构变量声明
struct struct_label{

} var_name; // 结构标记与变量同时声明

typedef struct {

} struct_type, *p_struct_type; // 结构typedef名声明
struct_type var_name; // 结构变量声明
p_struct_type var_name; // 结构指针变量声明

typedef struct struct_label{

} struct_type, *p_struct_type; // 结构标记与typedef名同时声明

typedef struct node{
ElemType data;
struct node *next;
} Node, *PNode; // 链表结点结构体典型声明