跳转至

输入输出

cin, cout

cin, cout 是 C++语言的输入输出语句

#include <iostream>

using namespace std;

int main() {
    int a, b;
    cin >> a >> b;

    cout << a + b;

    return 0;
}

This operator (>>) applied to an input stream is known as extraction operator. (Extracts and parses characters sequentially from the stream)

This operator (<<) applied to an output stream is known as insertion operator. (inserts them into the output stream)

多个变量的输入输出

int main() {
    int a, b, c;
    cin >> a >> b >> c;

    cout << a << ' ' << b << ' ' << c;

    return 0;
}

// 3个变量,使用空格隔开
// 输出的时候,使用<<符号,进行连接

scanf, printf

scanf, printf 是C语言的输入输出语句,叫做“格式化输入输出语句”

#include <cstdio>

using namespace std;

int main() {
    int a, b;
    scanf("%d%d", &a, &b);

    printf("%d", a + b);

    return 0;
}

占位符的对应关系

int %d
double %lf
char %c
long long %lld

有格式的输入

// 读入时间格式 12:09
int h, m;
scanf("%d:%d", &h, &m);

有格式的输出

// 输出 1+2=3,这种格式
printf("%d+%d=%d", a, b, a + b);

多个变量的输入输出

int main() {
    int a, b, c;
    scanf("%d%d%d", &a, &b, &c);

    printf("%d %d %d", a, b, c);

    return 0;
}

// 3个变量,使用空格隔开
// 输出的时候,printf双引号里面,直接用空格隔开
// 占位符与后面要输出的变量一一对应

保留小数点问题

第1种写法(最常用)

#include <cstdio>

double x = 3.14159;
printf("%.2lf", x);  // 输出一个小数
#include <cstdio>

double x = 1.23, y = 4.56;
printf("%.2lf %.2lf", x, y);  // 输出两个小数,中间用空格隔开

第2种写法(阅读程序有时会遇到,平时不这么写)

#include <iomanip>

double x = 3.14159;
cout << fixed << setprecision(2) << x;