C++格式输出

格式化输入输出

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

头文件是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;

}