java输入一个字符给c赋值_C语言的混合输入数字和字符问题

假如你的程序同时需要使用getchar()进行字符输入和使用 scanf()进行数字输入.这两个函数的每一个都能很好的完成工作,

但是它们不能很好地混合在一起.这是因为getchar()读取每个字符,包括空格,制表符和换行符;而scanf()在读取数字时候则

会跳过空格,制表符和换行符.下面是个例子,

char1.cpp/*C语言一个I/O问题程序*/

#include

void display(char cr,int lines,int width);

int main(void)

{

int ch;

int rows,cols;

printf("Enter a character and tow integers:\n");

while((ch=getchar())!='\n')

{

scanf("%d %d",&rows,&cols);

display(ch,rows,cols);

printf("Enter another character and tow integers;\n");

printf("Enter a newline to quit.\n");

}

printf("Bye.\n");

return 0;

}

void display(char cr,int lines,int width)

{

int row ,col;

for(row =1;row<=lines;row++)

{

for(col=1;col<=width;col++)

{

putchar(cr);

}

putchar('\n');

}

}

结果输出:Enter a character and tow integers:

d 3 2

dd

dd

dd

Enter another character and tow integers;

Enter a newline to quit.

Bye.

Press any key to continue...

可以看见紧跟在2后面的那个换行符,scanf()函数将该换行符留在了输入队列中.而getchar()并不跳过换行符,所以在循环的

下一周期,在你有机会输入其他内容之前,这个换行符由getchar()读出,然后将其赋值给ch,而ch为换行符正是终止循环的条件.

要解决这个问题,必须跳过一个输入周期中键入的最后一个数字与下一行开始处键入的字符之间的所有换行符或空格.

改进如下:char2.cpp

/*C语言一个I/O问题程序修改版本*/

#include

void display(char cr,int lines,int width);

int main(void)

{

int ch;

int rows,cols;

printf("Enter a character and tow integers:\n");

while((ch=getchar())!='\n')

{

if( scanf("%d %d",&rows,&cols)!=2)

break;

display(ch,rows,cols);

while(getchar()!='\n')      /*剔除掉scanf()输入后的所有字符.*/

{

printf("1");          /*后面有多少字符就输出多少个1*/

continue;

}

printf("Enter another character and tow integers;\n");

printf("Enter a newline to quit.\n");

}

printf("Bye.\n");

return 0;

}

void display(char cr,int lines,int width)

{

int row ,col;

for(row =1;row<=lines;row++)

{

for(col=1;col<=width;col++)

{

putchar(cr);

}

putchar('\n');

}

}

输出结果:Enter a character and tow integers:

d 3 4

dddd

dddd

dddd

Enter another character and tow integers;

Enter a newline to quit.

d 3 4

dddd

dddd

dddd

11Enter another character and tow integers;

Enter a newline to quit.

posted on 2006-11-03 14:12 matthew 阅读(1782) 评论(1)  编辑  收藏 所属分类: 数据结构与算法设计

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值