C++ 标准输入输出流

73 阅读2分钟

一、标准输入流 (cin)

1. 基本输入操作

int x;
cin >> x;  // 读取整数,遇非数字终止

string s;
cin >> s;  // 读取字符串,遇空格/Tab/换行终止

2. 行读取与字符读取

char buffer[100];
cin.getline(buffer, 100, '\n');  // 读取一行(含空格),最多99字符
// 第三个参数为终止字符(默认'\n'),会被提取但不存储

char ch = cin.get();  // 读取单个字符(含空白符)

3. 流控制操作

// 忽略字符
cin.ignore(100, '\n');  // 忽略最多100字符,直到遇到换行符

// EOF 检测循环
while (cin >> x) { 
    // Windows: Ctrl+Z, Linux/Mac: Ctrl+D 输入EOF终止
}

二、标准输出流 (cout)

1. 基本输出操作

cout.put('A').put('!');  // 链式字符输出

int n = 255;
cout << hex << n << endl    // ff (十六进制)
     << dec << n << endl    // 255 (十进制)
     << oct << n << endl;   // 377 (八进制)

image.png

2. 格式化输出

#include <iomanip>

double pi = 3.14159265;
cout << fixed << setprecision(2) << pi;  // 3.14 (固定小数位)

cout << setw(10) << "Hello" << endl;     // "     Hello" (宽度10)
cout << setfill('*') << setw(8) << 42;   // ******42

image.png

3. 域宽控制特性

char str[10];
cin.width(5);        // 设置输入域宽
cin >> str;          // 最多读取4字符(保留1位给'\0')
cout << str << endl;

cin >> str;          // 域宽设置仅生效一次
cout << str << endl; // 后续读取不受影响

image.png


三、文件输入输出流

1. 文件流基本操作

#include <fstream>

ifstream fin("input.txt");        // 输入文件流
ofstream fout("output.txt", ios::out | ios::app); // 输出文件流

int data;
fin >> data;                     // 从文件读取
fout << "Result: " << data;      // 写入文件

fin.close();                     // 显式关闭文件
fout.close();

2. 文件打开模式

模式标志说明
ios::in读取(默认ifstream)
ios::out写入(覆盖,默认ofstream)
ios::app追加写入(保留原内容)
ios::ate打开时定位到文件末尾
ios::binary二进制模式

3. 文件指针操作

// 输出流指针操作 (写位置)
ofstream fout("data.bin", ios::ate);
long pos = fout.tellp();         // 获取当前写位置

fout.seekp(20, ios::beg);        // 从开头移动20字节
fout.seekp(-5, ios::cur);        // 从当前位置回退5字节
fout.seekp(10, ios::end);        // 从结尾前移10字节

// 输入流指针操作 (读位置)
ifstream fin("data.bin");
long pos = fin.tellg();          // 获取当前读位置
fin.seekg(0, ios::end);          // 跳转到文件末尾

四、关键补充说明

  1. 流状态检测

    if (!cin) { // 检查流状态
        if (cin.eof()) cout << "EOF reached";
        if (cin.fail()) cin.clear(); // 清除错误状态
    }
    
  2. 二进制文件操作

    ofstream bin("data.bin", ios::binary);
    bin.write(reinterpret_cast<char*>(&data), sizeof(data));
    
  3. 字符串流用法

    #include <sstream>
    stringstream ss;
    ss << "Price: " << 99.9;
    string s = ss.str(); // "Price: 99.9"
    
  4. 格式标志持久性

    cout << hex << 255;     // ff
    cout << 100;            // 64 (仍为十六进制)
    cout << dec;            // 恢复十进制