您的位置:首页 > 编程语言 > C语言/C++

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

2017-10-05 00:37 549 查看
昨天有朋友问这个,顺便总结一下

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 <cruntime.h>
#include <stdio.h>
#include <dbgint.h>
#include <stdarg.h>
#include <file2.h>
#include <internal.h>
#include <mtdll.h>

/***
*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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: