如题。
素材
//△▽○◇□☆▲▼●◆■★¤◎√×卍卐↑←↓→↖↗↙↘◥◤◣◢
//╢╤┝┞┟┠┡┢═╞╟╡╪┭┮┯┰┱┲║╥╧╨╫┥┪┧┨┩┦┽┾┿╀╁╂┵┶┷┸┹┺╄╅╆╇╈╉╃╊
//┌┬┐┏┳┓╔╦╗╭─╮ ┍┑┎┒╒╕╓╖
//├┼┤┣╋┫╠╬╣│╳┃ ┕┙┖┚╘╛╙╜
//└┴┘┗┻┛╚╩╝╰━╯
随机数
随机生成一个0~N-1的整数。
C语言在 stdlib.h 库中内置了生成随机数的函数 rand() 。
引入随机种子time(0)。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
const int N=100;
int main()
{
srand(time(0));
printf("%d",rand()%N);
return 0;
}
清屏
#include <stdio.h>
#include <windows.h>
int main()
{
printf("dfhajfhdshfa");
system("CLS");
return 0;
}
运行结果:
移动光标位置
在控制台界面指定位置输出制定内容。
获取光标当前位置。
#include <stdio.h>
#include <windows.h>
HANDLE hOut=GetStdHandle(STD_OUTPUT_HANDLE);
void gotoxy(HANDLE hOut, int x, int y);
void getxy(HANDLE hOut, int &xx, int &yy);
void gotoxy(HANDLE hOut, int x, int y)
{
COORD pos;
pos.X=x;
pos.Y=y;
SetConsoleCursorPosition(hOut,pos);
}
void getxy(HANDLE hOut,int &xx,int &yy)
{
CONSOLE_SCREEN_BUFFER_INFO screen_buffer_info;
GetConsoleScreenBufferInfo(hOut, &screen_buffer_info);
xx=screen_buffer_info.dwCursorPosition.X;
yy=screen_buffer_info.dwCursorPosition.Y;
}
int main()
{
//可以把控制台想象成一个坐标系
//坐标仅由自然数表示
//左上角为(0,0),先列后行
//调试以下代码自行感受
gotoxy(hOut,1,3); //把光标移动到控制台的制定位置
printf("*");
int x,y;
getxy(hOut,x,y);//获取当前光标位置赋值给x和y
printf("\n%d %d",x,y);
return 0;
}
运行结果:
使程序暂停运行一段时间
没隔一会儿输出一行qwq
#include <stdio.h>
#include <windows.h>
int main()
{
for (int i=1;i<=10;++i)
{
printf("qwq\n");
Sleep(1000);//参数自己指定
}
}
从键盘获取读入
常用的scanf等读入方式需要按下回车程序才会去读取。
这里使用getch()或getche()读入字符的方式获取用户操作,使用方法类似于getchar函数。
这两个函数之间也有一点区别,有兴趣可以自己搜索一下。
#include <conio.h>
#include <stdio.h>
int main()
{
char x=getch();
putchar(x);
}
/*#include <conio.h>
#include <stdio.h>
int main()
{
char x=getche();
putchar(x);
}*/
判断用户是否输入
在不打断程序运行的情况下判断用户是否进行了输入,若用户进行了输入则获取输入。
#include <conio.h>
#include <stdio.h>
int main()
{
for (int i=1;i<=100;++i)
{
for (int j=1;j<=500;++j)
{
if (kbhit())
{
char x=getch();
putchar('\n');
}
}
printf("%d ",i);
}
}
隐藏光标
如果觉得光标闪烁很丑陋的话qwq
#include <stdio.h>
#include <windows.h>
void hide()
{
HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO CursorInfo;
GetConsoleCursorInfo(handle, &CursorInfo);
CursorInfo.bVisible = false;
SetConsoleCursorInfo(handle, &CursorInfo);
}
void ehide()
{
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
CONSOLE_CURSOR_INFO CursorInfo;
GetConsoleCursorInfo(handle, &CursorInfo);
CursorInfo.bVisible=true;
SetConsoleCursorInfo(handle, &CursorInfo);
}
int main()
{
hide();
getchar();
ehide();
getchar();
}
改变控制台背景颜色及文字颜色
#include <stdio.h>
#include <windows.h>
void setColor(unsigned short ForeColor=7,unsigned short BackGroundColor=0)
{
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);//获取当前窗口句柄
SetConsoleTextAttribute(handle,ForeColor+BackGroundColor*0x10);//设置颜色
}
int main()
{
for (int i=0;i<=15;++i,printf("\n"))
for (int j=0;j<=15;++j) setColor(j,i),printf("qwq");
}