标准输入输出

内容简介

输入输出用于让程序和外部交互。学习 C++ 时先掌握 std::cout / std::cin,再了解 C 风格的 printf / scanf,这样既能写 C++ 代码,也能读懂常见 C 示例。

用法

C++ 输入输出

#include <iostream>
#include <string>
 
int main()
{
    int age = 0;
    std::string name;
 
    std::cin >> name >> age;
    std::cout << name << " " << age << std::endl;
    return 0;
}

读取一整行

#include <iostream>
#include <string>
 
int main()
{
    std::string line;
    std::getline(std::cin, line);
    std::cout << line << std::endl;
    return 0;
}

C 风格输出

#include <stdio.h>
 
int main(void)
{
    printf("Hello World\n");
    printf("age = %d, score = %.1f\n", 18, 95.5);
    return 0;
}

C 风格输入

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

最佳代码实践

  • C++ 代码中优先使用 std::cinstd::coutstd::string
  • 使用 scanf 时,普通变量要传地址,例如 &age
  • 输出浮点数时明确格式,例如 %.2f 表示保留两位小数。
  • 不建议在头文件或大项目中写 using namespace std;,容易造成命名冲突。

错误用法

int age = 0;
scanf("%d", age);  // 错误:scanf 需要变量地址
std::cout << name << age;  // 不一定错误,但输出会粘在一起

注意事项

  • std::cin >> str 遇到空格会停止读取;读取一整行字符串时使用 std::getline
  • printf / scanf 在 C 接口、旧代码和算法题解析中很常见,基础阶段能看懂即可。
  • C 的格式占位符见 占位符和ASCII码

学习路径