C Primer Plus(6th)

scanf函数

2020-11-11  本文已影响0人  akuan

正面是一个混合输入字符和数字的程序:

#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 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.\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 two integers:
|c 1 2
cc
Enter another character and two integers;
Enter a newline to quit.
|! 3 6
!!!!!!
!!!!!!
!!!!!!
Enter another character and two integers;
Enter a newline to quit.
Bye.

getchar()读取所有字符,包括空白、制表符、换行符。
scanf()读取字符时会跳过空白、制表符、换行符。
对于以上代码中while ((ch = getchar()) != '\n')中的getchar()函数,等待从键盘输入,输入c 1 2后,按下Enter键。此时缓冲区是:“'c',␠,1,␠,2,␊”,这时getchar()从缓冲中读取一个字符'c',ch='c',此时缓冲区为“␠,1,␠,2,␊”。紧接着while循环体中if (scanf("%d %d",&rows, &cols) != 2),即scanf函数从缓冲区中读取出匹配模式:"%d %d"的两个元素,这时scanf先跳过␠,然后刚好匹配“1,␠,2”。最后缓冲区只有“␊”了,即'\n'。

上一篇下一篇

猜你喜欢

热点阅读