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

C语言格式化输入/输出

2016-01-18 22:10 417 查看



int printf:-- formatted output(格式化输出)

SYNOPSIS(梗概 )

     printf format [arguments
...]

DESCRIPTION

     The printf utility formats and prints its arguments, after the first,

     under control of the format.  The
format is a character string which con-

     tains three types of objects: plain characters, which are simply copied

     to standard output, character escape sequences which are converted and

     copied to the standard output, and format specifications, each of which

     causes printing of the next successive
argument.

     format在这里应该译为格式串,上
4000
面已经说明了格式串是一种含有三种东西的字符串,分别是1.直接的从标准化输出copy过来的字符 2.从标准化输出经过转换然后copy的字符3.格式串说明,也可以说是「转换说明」(conversion specifications)

     注意上文的successive是「连续」的意思。

     

     最值得说的应该就是这个conversion specifications了,我们只需要了解它的常见的用法

     %m.pX

-----m表示最小字段宽度(minimum field width),m指定了要显示的最少字符数量。如果要显示的数值所需字符数少于m,那么值在字段内是右对齐的,当然它可以自动扩充而不会丢失数据,m前放负号可以左对齐。

-----关于.p就是控制在小数点后面多少位的问题,不同的编译器对此貌似差别蛮大,clang反正如果不强转,int是不能用f的。

-----X表示变量的值到底(可能)是什么类型,d表示十进制整数,f表示浮点数,一个l表示long,两个l表示long long,还有u表示unsigned,特别要注意的是我个人偏好的double应该用ld。

      值得一提的是上次做题有人用%X和%x过了转16进制...还有%O和%o八进制。

-----m和.p都是可选的。

int scanf(const
char
*restrict format,
...);(格式化输入)

     scanf函数非常复杂,这个系列里面的以后还有很多。受限指针貌似是C99加的,还不懂就先不说了。

     

     The scanf() family of functions scans input according to a
format, 

     as described below.  This format may contain conversion
specifiers;

     the results from such conversions, if any, are stored through the 

     pointer arguments. The scanf() function reads input from the standard 

     input stream stdin.

     「scans input」说得很妙,因为scarf函数的工作方法就是这样做的:

      假设用户录入三行:

1(换行)

-20   .3(换行)

             -4.0(换行)

      那么实际上它会把输入看成一个输入流:1(换行)-20···.3(换行)····-4.0(换行)(·表示空格)

      寻找的开始,scanf函数会自动忽略空白字符(white-space character 含有有空格和换行),在要求读入整数的时候,scanf函数首先寻找负号然后寻找数字,然后可能会有小数点等等,结尾的换行符scanf会自动地把它「丢弃」,并没有读取它。它会被下一个scanf「忽略」。

      scanf需要的是变量的地址,这一点不多说,自己要多多注意。你想读入指针地址的话用%p。

      scanf和printf都是有返回值的,有时候可以用来检测是否正确读入或输出多少字符了。

最后贴一下朋友骗过OJ的代码:

#include<stdio.h>

int main()
{
int a;
scanf("%d",&a);
printf("%X",a);
return 0;
}

   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: