8说了,奋斗 2018-10-30 13:54 采纳率: 0%
浏览 642

关于 scanf 和 getchar 的while循环问题

初学萌新 求指教 !!!
错误程序:
#include
void display(char cr, int lines, int width);//打印字符的函数
int main(void)
{
int ch; //待打印字符
int rows, cols; //行数 列数
printf("Enter a character and two integers :\n");

scanf(" %c", &ch);  

while (ch != '\n')
{
if(scanf("%d%d", &rows, &cols)!=2)
break;

    display(ch, rows, cols);

    printf("Enter another character and two integers :\n");
    printf("Enter a newline to quit .\n");

    while (getchar() != '\n')//跳过前面多余的的输入
        continue;

    scanf("%c", &ch);   /*遇到的问题???*/
    //这里如果输入 回车换行符 ch赋值为 \n  为什么程序不退出循环呢?
    //如果用getchar() 简化所有的scanf()输入换行符 就能退出; 
}
printf("Bye !");
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');
}
}
正确程序:
下面是改过的函数
#include
void display(char cr, int lines, int width);
int main(void)
{
int ch;//待打印字符
int rows, cols;//行数 列数

printf("Enter a character and two integers :\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 newline to quit .\n");

//输入换行符即可退出
}
printf("Bye !");
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');
}
}
初学萌新 求指教 !!!
感谢耐心看完 感谢

  • 写回答

2条回答 默认 最新

  • sizeofname 2022-01-06 21:35
    关注

    楼主后来有弄懂吗?同问!

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题