一、快读
getchargetchargetchar,需要调用头文件cstdiocstdiocstdio,一次只能读取单个字符,但速度快于scanfscanfscanf。
getchargetchargetchar的使用方法:
char ch;
ch=getchar();
快读的基本原理就是对getchargetchargetchar读入的单个字符进行处理以达到快速读入的目的。
快读代码:(intintint 可根据需要改为其他类型,如 longlonglong longlonglong。)
int read()
{
int s=0,w=1;
char c=getchar();
while(c<'0'||c>'9')
{
if(c=='-')//判负
w=-1;
c=getchar();
}
while(c>='0'&&c<='9')//读入数字部分
{
s=s*10+c-'0';
c=getchar();
}
return s*w;
}
int a;
a=read();
或者也可以传递参数:
//传递参数版
void read(int &x)//必须加 &
{
x=0;
int w=1;
char c=getchar();
while(c<'0'||c>'9')
{
if(c=='-')
w=-1;
c=getchar();
}
while(c>='0'&&c<='9')
{
x=x*10+c-'0';
c=getchar();
}
x*=w;
return;
}
int a;
read(a);
二、快写
putcharputcharputchar,头文件cstdiocstdiocstdio,读入单个字符,快于printfprintfprintf。
char ch='a';
putchar(ch);
快写代码:
void print(int x)
{
if(x<0)//判负
{
putchar('-');
x=-x;
}
if(x>=10)
print(x/10);
putchar(x%10+'0');
return;
}
int a=123;
print(a);
三、快读和快写的使用条件
1.确保需要读入/输出的是整型;
2.如果数据范围小则最好不要使用快读快写,如果数据范围大则一定要使用快读快写。
这篇博客介绍了C++中提高输入输出效率的方法。包括快读(利用getchar处理单个字符)和快写(使用putchar进行单个字符输出),并提供了相应的代码示例。同时强调了快读快写的适用条件,即适用于处理整型数据且在大数据范围时效果更佳。
676

被折叠的 条评论
为什么被折叠?



