频道栏目
首页 > 资讯 > C语言 > 正文

C语言的scanf函数输入方式分析

17-10-05        来源:[db:作者]  
收藏   我要投稿

C语言在定义scanf函数时,已经包含头文件stdio.h,所以用scanf时,不用添加头文件

int main(void)
{
    char a;
    scanf("%c",&a);
    printf("%c\n",a);
    return 0;
}

是完全没有问题的。

scanf函数没有精度控制 如:scanf("%4.8f",&a)是非法的
但宽度是有控制的 如:scanf("%3d",&a)是完全可以的

在输入多个数值时,输入数据之间的间隔可用 空格,TAB键 或 回车键

当程序编译遇到 空格,TAB键,回车键,非法数据(如对 “%d” 输入 “3H”时,H为非法字符 )即认为该数据结束

可能的问题:
(1)

    int a,b;
    scanf("%3d%3d",&a,&b);
  //输入123456789,程序会将123赋值给a,456赋值给b,其余部分被截去

(2)

    char a,b;
    scanf("%c%c",&a,&b);
    printf("%c%c\n",a,b);
 //scanf函数中"%c%c"之间没有空格,输入q w(q空格w)的时候,输出结果只有q
 //若输入qw,就不会有问题,输出结果是qw

(3)
最后附上scanf实现源码

/***
*scanf.c - read formatted data from stdin
*
*       Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved.
*
*Purpose:
*       defines scanf() - reads formatted data from stdin
*
*******************************************************************************/

#include 
#include 
#include 
#include 
#include 
#include 
#include 

/***
*int scanf(format, ...) - read formatted data from stdin
*
*Purpose:
*       Reads formatted data from stdin into arguments.  _input does the real
*       work here.
*
*Entry:
*       char *format - format string
*       followed by list of pointers to storage for the data read.  The number
*       and type are controlled by the format string.
*
*Exit:
*       returns number of fields read and assigned
*
*Exceptions:
*
*******************************************************************************/

int __cdecl scanf (
        const char *format,
        ...
        )
/*
 * stdin 'SCAN', 'F'ormatted
 */
{
        int retval;

        va_list arglist;

        va_start(arglist, format);

        _ASSERTE(format != NULL);

        _lock_str2(0, stdin);

        retval = (_input(stdin,format,arglist));

        _unlock_str2(0, stdin);

        return(retval);
}
相关TAG标签
上一篇:CSSbackground的详细使用
下一篇:jquery扩展方法
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站