c 语言中混合输入字符和数字( c primer plus 中的程序 )

该博客介绍了一个C语言程序,用于混合输入字符和两个整数。程序使用`getchar()`读取字符,`scanf()`读取整数,并通过`display()`函数显示字符构成的矩阵。文章指出原程序存在的问题——在第二次输入时因` `导致循环提前结束,并提供了两种解决方案:一种是额外的`while`循环来处理剩余的` `,另一种是使用`getchar()`清除缓冲区。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个程序的核心是这段代码

while( ( ch = getchar() ) != '\n' )
    {
        scanf("%d %d", &rows, &cols ) ;
        display( ch, rows, cols ) ;
        printf("Enter another character and two integers:\n") ;
        printf("Enter a newline to quit.\n") ;
    }

所谓的混合输入字符和数字奥妙也就在这其中。。

 

#include <stdio.h>
#include <stdlib.h>
void display( char cr, int lines, int width ) ;
int main()
{
    int ch ;
    int rows, cols ;
    printf("Enter a character and two integers: \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 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') ;
    }
}

 

这个程序的瑕疵。。。。就是只能输入输出一遍,因为在第二次再到达大while循环时,上次的'\n'在这里找到了安放的位置,然后程序自然地跳出了循环。。。

然后怎么办呢,当然是改下了。

书上说的是

while( ( ch = getchar() ) != '\n' )
    {
        scanf("%d %d", &rows, &cols ) ;
        display( ch, rows, cols ) ;

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

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

 

然后网上面查了下,还有种经典的清除缓存的方法,如下:

while( ( ( c = getchar() ) != '\n' ) && c != EOF )  ;

这样子做是在任何情况下,缓冲区中的内容全部都会被清除干净,可谓是一劳永逸的方法呀。。。 


本文就作为我的个人笔记记录下来,没有太内涵的内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值