学习

来源:互联网 发布:休闲运动套装淘宝店 编辑:程序博客网 时间:2024/05/29 04:10
/*问题:while (getchar() != '\n')continue;   跳过一行的剩余字符getchar()读取每个字符,包括空格,制表符和换行符,scanf()在读取数字时,会跳过空格制表符,换行符。时间:2016/4/16*/#include <stdio.h>void display(char ch, int height, int width);int get_int(void);int main(void){int ch;int rows, cols;printf("enter a character and two integers:\n");while ((ch = getchar()) != '\n'){/*if (scanf_s("%d %d", &rows, &cols) != 2)   //输入错误类型,终止输入,退出break;*/rows=get_int();//给用户尝试输入正确类型的机会cols=get_int();if (rows < 0 || cols < 0){printf("您输入的有不是正整数,请再次输入2个正整数:");rows = get_int();cols = get_int();}display(ch, rows, cols);while (getchar() != '\n')//scanf()函数将换行符留在了队列中。所以需要将换行符跳过,否则程序运行一次就结束。continue;printf("enter another character and two integers;\n");printf("enter a newline to quit.\n");}return 0;}void display(char ch, int height, int width){for (int row = 0; row < height; row++){for (int col = 0; col < width; col++)putchar(ch);putchar('\n');}}/*要求输入整型,给用户尝试输入正确类型的机会。首先需要提出哪些有问题的输入;如果scanf()没有输入成功,就会将其留在输入队列中。可以使用getchar()逐个字符地读取,也可以如下做:*/int get_int(void){int input;char ch;while (scanf_s("%d", &input) != 1){while ((ch = getchar()) != '\n')putchar(ch);//剔除错误输入printf("is not an integer,\n please enter an integer value, such as 1 ,-4 or 9: ");}return input;}
</pre><pre code_snippet_id="1649962" snippet_file_name="blog_20160416_3_4937912" name="code" class="cpp">


0 0
原创粉丝点击