首页 > 学院 > 开发设计 > 正文

7.1 printf与scanf

2019-11-06 07:36:30
字体:
来源:转载
供稿:网友

1.格式化的输入输出

PRintf 返回输出的字符数 %[flags][width][.prec][hlL]typescanf 返回读入的项目数 %[flag]type 在要求严格的程序中,应该判断每次调用scanf或printf的返回值,从而了解程序运行中是否存在问题#include<stdio.h>int main(int argc, const char *argv){ int num; int i1 = scanf("%i", &num);//输入123 int i2 = printf("%d/n", num);//输出123 printf("%d:%d/n", i1, i2);//输出1:4 return 0;}

2. printf

2.1 flag

-:左对齐 +:在前边放+或- (space):正数留空 0:用0填充

#include <stdio.h>int main(int argc, const char *argv){ printf("%9d/n", 123); // 123 占9位,右对齐,123前边补6个空格 printf("%-9d/n", 123); //123 printf("%+9d/n", 123); // +123 占9位,右对齐,+123前边补5个空格 printf("%+-9d/n", 123);//+123 printf("%-+9d/n", 123);//+123 printf("%-+9d/n",-123);//-123 printf("%09d/n", 123);//000000123 printf("%-09d/n",-123);//-123 return 0;}

2.2 width 或 prec

number:最小字符数 *:下一个参数是字符数 .number:小数点后的数位 .*:下一个参数是小数点后的位数

#include <stdio.h>int main(int argc, const char *argv){ printf("%*d/n", 6, 123);// 123 相当于%6d,占6位,123前加3个空格 printf("%9.2f/n", 123.4);// 123.40 return 0;}

2.3 类型修饰

hh:单个字节 h:short l:long ll:long long L:long double

#include <stdio.h>int main(int argc, const char **argv){ printf("%hhd/n", (char)12345); //57 printf("%9.2f/n", 123.4);// 123.40 占9位,123.40前加3个空格 return 0;}

2.4 type

i或d:int u:unsigned int g或G:float o:八进制 a或A:十六进制浮点数 x:字母小写的十六进制 X:字母大写的十六进制 c:char s:字符串 p:指针 f或F:默认显示6位小数的float e或E:指数 n:读入/写出的个数

3.scanf

3.1 flag

*:跳过 数字:最大字符数 hh:char h:short l:long,double ll:long long L:long double

#include<stdio.h>int main(){ int num; scanf("%d", &num); printf("%d/n", num); return 0;}

3.2 type

d:int s:字符串 i:整数,可能为十六进制或八进制 u:unsigned int o:八进制 x:十六进制 a,e,f,g:float c:char […]:所允许的字符 p:指针

#include<stdio.h>int main(int argc, const char *argv){ int num; scanf("%i", &num);//输入 0x12 printf("%d/n", num);//输出18 return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表