C++格式输出

标准输入输出与格式化编程详解
本文介绍了如何在编程中实现格式化输入输出,包括stdio.h头文件的使用,printf和scanf函数的基本操作,以及如何通过控制格式符调整输出样式。涵盖了变量的格式化输出、占位符技巧以及输入函数的使用实例。

格式化输入输出

格式化输入输出,也叫做标准输入输出,即从键盘输入,输出到屏幕上。

头文件是stdio.h,以下3种方法都可以导入:

1

#include <stdio.h>

1

#include <cstdio>

1

#include <bits/stdc++.h>

输出函数

printf,print就是打印,表示打印到屏幕上,f则是format、function的首字母,你可以理解成格式化输出、输出函数等。

例一:输出Hello World:

1

2

3

4

5

6

#include <bits/stdc++.h>

using namespace std;

int main(){

    printf("Hello World\n");

    return 0;

}

例二:输出变量的值

格式化输出函数,你需要输出什么,直接写在双引号里面,如果里面包含变量,只需要用格式符替换。

如输出“I'm 12 years old.”,

1

2

3

4

5

6

7

8

9

10

#include <bits/stdc++.h>

using namespace std;

int main(){

    int a;

    cin >> a;

    printf("I'm 12 years old.\n");

    printf("I'm a years old.\n");

    printf("I'm %d years old.\n", a);

    return 0;

}

例三:输出多个变量

如输出“The ascii of A is 65.”,其中字符由用户输入。

1

2

3

4

5

6

7

8

9

10

#include <bits/stdc++.h>

using namespace std;

int main(){

    int a;

    char b;

    cin >> b;

    a = b;

    printf("The ascii of %c is %d.\n", b, a);

    return 0;

}

输出技巧

场宽,即占多少个字符的宽度,可以在格式符中设置;不设置则默认有多少位就输出多少位。

1

2

3

4

5

6

7

8

9

10

11

12

13

#include <bits/stdc++.h>

using namespace std;

int main(){

    int a=123, b=45, c=6;

    double x=1.23456789;

    printf("a=%db=%dc=%d\n", a, b, c);

    printf("a=%d b=%d c=%d\n", a, b, c);

    printf("a=%-5db=%-5dc=%-5d\n", a, b, c);

    printf("a=%5d\nb=%5d\nc=%5d\n", a, b, c);

    printf("a=%05d\nb=%05d\nc=%05d\n", a, b, c);

    printf("x=%.2lf x=%5.2lf\n", x, x);

    return 0;

}

运行以上代码,你会发现“%5d”共占5位,不足5位前面补空格,即“右对齐”。

思考:如果输出的值是7位,用“%5d”会怎样?“%-10d”呢?

输入函数

scanf,scan就是扫描,用于输入;f表示格式化、函数;其用法与printf累死,需要注意的是,输入时需要加入取地址符号“&”。

例三:输出两个整数的差

1

2

3

4

5

6

7

8

#include <bits/stdc++.h>

using namespace std;

int main(){

    int a, b;

    scanf("%d%d", &a, &b);

    printf("%d\n", a-b);

    return 0;

}

输入技巧

注意:输入输出技巧有所不同,书上讲到的、自己验证过的才能使用。

例四:输出生日

输入8位数字表示小明的出生年月日,输出小米的生日,如输入20191207,输出12-07。

1

2

3

4

5

6

7

8

#include <bits/stdc++.h>

using namespace std;

int main(){

    int a, b;

    scanf("%*4d%2d%2d", &a, &b);

    printf("%02d-%02d\n", a, b);

    return 0;

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值