输入/输出

SyEic_L MVP++

I/O类库基本类

ios

​ istream

​ —ifstream

​ —istringstream

​ ostream

​ —ofstream

​ —ostringstream

面向控制台的I/O

  • cin(istream的对象)
  • cout(ostream的对象)
  • cerr和clog(ostream的对象):对应特殊信息(如错误信息),cerr不带缓冲,clog带缓冲

控制台输出操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
......
int x;
float f;
char ch;
int *p=&x;
......
cout << x ; //输出x的值。
cout << f; //输出f的值。
cout << ch; //输出ch的值。
cout << "hello"; //输出字符串"hello"。
cout << p; //输出变量p的值,即,变量x的地址。

cout << x << f << ch << "hello" << p;

控制台输入操作

1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
......
int x;
double y;
char str[10];
cin >> x; cin >> y; cin >> str;
或者
cin >> x >> y >> str;

面向文件的I/O

  • 文本方式(text)
  • 二进制方式(binary)

文件输出操作

  • 打开文件:创建一个ofstream类的对象

    • 直接方式
      ofstream out_file(<文件名> [,<打开方式>]);

      例如:
      ofstream out_file("d:\\myfile.txt",ios::out);

    • 间接方式
      ofstream out_file;
      out_file.open(<文件名> [,<打开方式>]);

      例如:

      out_file.open("d:\\myfile.txt",ios::out);

  • 判断打开是否成功

    1
    2
    3
    4
    5
    6
    7
    if (!out_file.is_open()) //或:out_file.fail()

    //或:!out_file

    { ...... //失败处理

    }
  • 输出数据

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    int x=12;
    double y=12.3;
    ......
    //以文本方式输出数据
    ofstream out_file("d:\\myfile.txt",ios::out);
    if (!out_file) exit(-1);
    out_file << x << ' ' << y << endl; //输出:12 12.3

    //以二进制方式输出数据
    ofstream out_file("d:\\myfile.dat",ios::out|ios::binary);
    if (!out_file) exit(-1);
    out_file.write((char *)&x,sizeof(x)); //输出:4个字节
    out_file.write((char *)&y,sizeof(y)); //输出:8个字节
  • 关闭文件
    out_file.close();
    目的:把文件内存缓冲区的内容写到磁盘文件中

  • 以文本方式输出的文件要以文本方式输入,以二进制方式输出的文件要以二进制方式输入

  • Title: 输入/输出
  • Author: SyEic_L
  • Created at : 2025-04-10 08:31:30
  • Updated at : 2025-04-10 08:31:30
  • Link: https://blog.syeicl.vip/2025/04/10/输入-输出/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments