C++ 基本的输入输出

在 C++ 中,最常用的输入输出来自于 <iostream> 头文件,主要通过以下四个对象完成:

  • std::cin:标准输入流,通常绑定到键盘
  • std::cout:标准输出流,通常绑定到屏幕
  • std::cerr:标准错误流,未缓冲,用于输出错误信息
  • std::clog:标准日志流,带缓冲,用于输出日志信息

下面分几部分介绍基本用法和常见技巧。


1. 控制台输出 — std::cout

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    std::cout << "数字:" << 42 << "\n";
}
  • operator<< 支持链式调用
  • std::endl:输出换行并刷新缓冲区
  • "\n":只输出换行,不自动刷新(性能更好)

常用格式控制(<iomanip>)

#include <iostream>
#include <iomanip>

int main() {
    double pi = 3.1415926;
    std::cout 
        << "默认精度: "  << pi << "\n"
        << "设定小数点后 3 位: " 
        << std::fixed << std::setprecision(3) << pi << "\n"
        << "科学计数法: " 
        << std::scientific << pi << "\n";
}
  • std::fixedstd::scientific:切换浮点格式
  • std::setprecision(n):设置有效数字或小数位数(配合 fixed)
  • std::setw(w):设定字段宽度
  • std::leftstd::right:对齐方式

2. 控制台输入 — std::cin

#include <iostream>
#include <string>

int main() {
    int    a;
    double b;
    std::string name;

    std::cout << "请输入两个数 a b: ";
    std::cin  >> a >> b;           // 遇空白(空格、回车)分隔
    std::cout << "请输入你的姓名: ";
    std::cin  >> name;             // 只读到第一个空白前

    std::cout << "你好," << name 
              << ",a+b = " << (a + b) << "\n";
}
  • operator>> 也可链式调用
  • 遇到非法输入时,流会进入“失败”状态,可用 std::cin.fail() 检查并用 std::cin.clear()std::cin.ignore() 恢复

读取包含空格的整行

#include <iostream>
#include <string>

int main() {
    std::string line;
    std::cout << "请输入一行文字: ";
    std::getline(std::cin, line);   // 读取整行,包括空格
    std::cout << "你输入了: " << line << "\n";
}

注意:若在调用 std::getline 前已有一次 operator>>,需要先用

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

丢弃剩余的换行符。


3. 错误与日志输出 — std::cerrstd::clog

#include <iostream>

int main() {
    std::cerr << "错误:文件打开失败!\n";  // 立即输出
    std::clog << "日志:程序开始运行\n";    // 带缓冲,适合大量日志
}
  • std::cerr 无缓冲,输出即时
  • std::clog 带缓冲,可配合日志等级使用

4. 文件 I/O — \<fstream\>

#include <fstream>
#include <iostream>
#include <string>

int main() {
    // 写文件
    std::ofstream ofs("output.txt");
    if (!ofs) {
        std::cerr << "无法打开 output.txt 进行写入\n";
        return 1;
    }
    ofs << "Hello, file!\n" << 123 << "\n";
    ofs.close();

    // 读文件
    std::ifstream ifs("output.txt");
    if (!ifs) {
        std::cerr << "无法打开 output.txt 进行读取\n";
        return 1;
    }
    std::string line;
    while (std::getline(ifs, line)) {
        std::cout << line << "\n";
    }
    ifs.close();
}
  • std::ofstream:输出文件流(写)
  • std::ifstream:输入文件流(读)
  • std::fstream:读写都可
  • 同样支持 operator<</operator>> 与 std::getline
  • 可用 ofs.open(path, std::ios::app) 以追加方式打开

5. 常见小贴士

  1. 尽量使用 "\n" 而非 std::endl,避免不必要的刷新带来的性能损耗。
  2. 检查流状态fail()eof())以保证健壮输入。
  3. 混合使用 operator>> 与 getline 时注意丢弃换行符
  4. 打开文件前先判断路径与权限,并在结束后及时 close()(或让析构自动关闭)。
  5. 对于二进制数据,打开时加上 std::ios::binary 模式,并用 read()/write() 处理原始字节。

掌握以上基础,就能在大多数控制台和文件 I/O 场景下游刃有余。

类似文章

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注