C中的获取输入函数

来源:互联网 发布:mac汉字字体下载 编辑:程序博客网 时间:2024/04/20 11:05

getchar(),scanf()
这两个函数中的每一个都能很好地完成其工作,但他们不能很好地混合在一起。这是因为getchar()读取每个字符,包括空格、制表符和换行符;而scanf()在读取数字时则跳过空格、制表符和换行符。
showchar1.c
#include<stdio.h>
void  display(char cr,int lines,int width);
int main(void)
{
int ch;
int rows,cols;
printf("Enter a character and two number:/n");
while((ch=getchar())!='/n')
{
scanf("%d %d",&rows,&cols);
display(ch,rows,cols);
printf("Enter another character and two integers/n    ");
printf("Enter a new line to quit./n");
}
printf("Bye./n");
return 0;
}
void display(char ch,int lines,int width)
{
int row,col;

for(row=1;row<=lines;row++)
{
for(col=1;col<=width;col++)
{
putchar(ch);
}
putchar('/n');
}
}


showchar2.c
#include<stdio.h>
void  display(char cr,int lines,int width);
int main(void)
{
int ch;
int rows,cols;
printf("Enter a character and two number:/n");
while((ch=getchar())!='/n')
{
if(scanf("%d %d",&rows,&cols)!=2)
break;
display(ch,rows,cols);
while(getchar()!='/n')
continue;
printf("Enter another character and two integers/n    ");
printf("Enter a new line to quit./n");
}
printf("Bye./n");
return 0;
}

void display(char ch,int lines,int width)
{
int row,col;

for(row=1;row<=lines;row++)
{
for(col=1;col<=width;col++)
{
putchar(ch);
}
putchar('/n');
}
}

原创粉丝点击