细说C语言scanf()函数

来源:互联网 发布:淘宝电击棍 编辑:程序博客网 时间:2024/06/05 07:51

说起scanf()函数,相信大家一定不会陌生,可能你会说不就是输入的时候用吗?这么说也没错,我也和大家一样一开始对他它认识仅此而已,直到我碰到问题花了好长时间没有解决,百度也没找到答案,才发现我仅仅只是了解scanf()函数的皮毛.
下面把我碰到问题以及解决方案拿出来分享下,给那些也碰到过此问题的新手共勉,大神勿喷!
实现功能:判断输入是否为整数,若为整数则保留,否则重新输入.


#include <stdio.h>int main(){        int i;        printf("Please input an int:");        while(!scanf("%d",&i))                printf("You input data is not int,please try input again:");        printf("You input number is %d\n",i);        return 0;}

这个代码初看逻辑没问题,可是运行起来如果输入首字符不是数字,输出就是个死循环.
运行结果:
error code!
在scanf()查看文档:The scanf() function reads input from the standard input stream stdin;意思就是scanf()函数读取标准输入流;查资料得知输入匹配成功时该函数返回匹配的个数,第一个匹配失败则返回值为0.这看似也没问题,然后查了其他资料大部分说的就是用fflush(stdin),刷新输入流,然而我试了根本没用,最后用一个getchar()搞定,上最后代码.

#include <stdio.h>#include <string.h>int main(){        int i;        printf("Please input an int:");        while(!scanf("%d",&i)){                while(getchar() != '\n')      //处理字符或字符串                        continue;                printf("You input data is not int,please try input again:");        }        printf("You input number is %d\n",i);        return 0;}

运行结果:
suceess code


Summarry:scanf()匹配第一个非空字符(匹配输入数字时)

0 0