首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

请优化下面的程序(急),该如何处理

2012-02-15 
请优化下面的程序(急)#includestdafx.h unsignedintcount0intprint(char*p){charchchgetchar()whil

请优化下面的程序(急)
#include   "stdafx.h "
unsigned   int   count=0;
int   print(char   *p)
{
char   ch;
ch=getchar();
while(ch!= 'q ')
{
if(count <112)
{
sprintf(p, "%03d.dat ",count);
puts(p);
count++;
ch=getchar();
continue;
}
}
return   1;
}
int   main(int   argc,   char*   argv[])
{
char   buff[20];
printf( "按任意键输出,按Q键退出:\n ");
print(buff);
return   1;
}


[解决办法]
if(count <112)语句外提,这样效率会更好些。
while(ch!= 'q ' && count <112)
{
sprintf(p, "%03d.dat ",count);
puts(p);
count++;
ch=getchar();
}


[解决办法]
int print(char *p )
{
int count = 0;
while( ( (char)getch() != 'q ') && ( count++ < 112 ) ) {
sprintf(p, "%03d.dat ",count);
puts(p);
}

return 1;
}

参数p不要或者要加上p的长度,sprintf要用snprintf防止缓冲区溢出

热点排行