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

来源:互联网 发布:手机淘宝怎么看vip等级 编辑:程序博客网 时间:2024/04/25 16:15

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

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 )  ;

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


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

原创粉丝点击