C语言 常用代码

本文将记录一些 C 语言和 C++ 中常用的代码。

一、读入直到文件末尾

1
2
3
while (scanf("%d", &n)) != EOF){

}

二、获取按键操作(无需按回车输入)

1
2
3
4
5
6
#include <conio.h>

if(kbhit()){ //按键按下,kbhit()为真;否则,kbhit()为假
input = getch(); //由input变量接收按下的键值
···
}

三、排序

1.C 语言版

1
2
3
#include <stdlib.h>

qsort(首元素地址, 排序个数, 数组中每个元素的大小, 比较函数);

2.C++ 版

1
2
3
4
#include <algorithm>
using namespace std;

sort(首元素地址, 首元素地址 + 排序个数, 比较函数cmp(选填));

四、随机数

1
2
3
4
5
6
7
#include <stdlib.h>
#include <time.h>

int main(){
srand((unsigned) time(NULL)); //初始化随机数发生器
int i = rand(); //获得随机数
}

五、暂停程序

1.system(“pause”)

1
system("pause");

2.getchar

1
getchar();

六、清屏

1.用清屏函数

可能会造成闪屏

1
2
3
#include <stdlib.h>

system("cls");

2.gotoxy

光标移动到指定位置

可以使光标移动到原点进行重画,实现类似清屏的效果

1
2
3
4
5
6
7
8
9
10
#include <windows.h>
void gotoxy(int x,int y){
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle,pos);
}

gotoxy(0,0);

七、隐藏光标

1
2
3
4
5
6
7
8
9
10
#include<windows.h>
void HideCursor(){
CONSOLE_CURSOR_INFO cursor;
cursor.bVisible = FALSE;
cursor.dwSize = sizeof(cursor);
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorInfo(handle, &cursor);
}

HideCursor();

参考