C++的标准输入输出

C++ 标准输入输出笔记

1. 标准输入输出类型对比

C++ 标准输入输出类型

  • 标准输入extern istream cin; (键盘输入)
  • 标准输出extern ostream cout; (显示屏输出)
  • 标准错误extern ostream cerr; (显示屏输出)
  • 标准日志extern ostream clog;

对应的 C 标准 IO 库和系统 IO 库

类型C 标准 IO 库系统 IO 库
标准输入stdin (FILE *)STDIN_FILENO (int)
标准输出stdout (FILE *)STDOUT_FILENO (int)
标准错误stderr (FILE *)STDERR_FILENO (int)

2. 使用 C++ 标准输出 cout

使用 cout 对象进行标准输出,不需要格式化字符,这是因为 << 操作符被重载了不同的数据类型。

ostream & operator << (ostream & out, int num);
ostream & operator << (ostream & out, float num);
ostream & operator << (ostream & out, const char *s);
ostream & operator << (ostream & out, const string &s);

示例代码

#include <iostream>
#include <string>

using namespace std;

struct Student {
    string name;
    int age;
};

int main() {
    int num1 = 100;
    float fnum = 3.14;
    const char *str = "hello";
    string s1 = "world";

    cout << num1 << " " << fnum << " " << str << " " << s1 << endl;

    Student stu = {"zhangsan", 22};
    // cout << stu << endl; // error: no match for 'operator<<'
}

3. 使用 C++ 标准输入 cin

重载的 >> 操作符

istream & operator >> (istream &in, int &num);
istream & operator >> (istream &in, float &fnum);
istream & operator >> (istream &in, char *&str);
istream & operator >> (istream &in, string &s);

示例代码

#include <iostream>
#include <string>

using namespace std;

struct Student {
    string name;
    int age;
};

int main() {
    int num;
    float fnum;

    cout << "Input an int number: ";
    cin >> num;
    cout << "Input a float number: ";
    cin >> fnum;
    cout << "num = " << num << ", fnum = " << fnum << endl;

    // 读取字符串
    char buf[128] = ""; // 栈内存: 可读可写
    cout << "Input a string: ";
    cin >> buf;
    cout << "buf = " << buf << endl;

    // 读取 C++ 字符串
    string name;
    cout << "Input another string: ";
    cin >> name;
    cout << "name = " << name << endl;

    // 读取 Student 对象
    Student stu;
    // cin >> stu; // error: no match for 'operator>>'

    // 读取整数和字符
    char ch;
    cout << "Input a number and a character: ";
    cin >> num >> ch; // 能正常输入,不会读取 '\n'
    cout << "num = " << num << ", ch = " << ch << endl;
}

4. C 标准 IO 和 C++ 标准 IO 的缓冲区

C 标准 IO 的缓冲区

  • C 标准 IO:scanf() 和 printf() 都带有缓冲区。
    • scanf() 在读取输入时会跳过空格和换行符,但不会处理回车符。
    • printf() 输出时会在缓冲区满或者遇到换行符时刷新输出。

C++ 标准 IO 的缓冲区

  • C++ 标准 IO:cin 和 cout 也带有缓冲区。
    • cin 会跳过空格字符,读取输入时会处理回车符。
    • cout 输出时也会在缓冲区满或者遇到换行符时刷新输出。
注意事项
  1. 使用 scanf 输入
    • 需要使用格式化字符指定输入数据类型,如 %d 表示整数,%f 表示浮点数,%s 表示字符串等。
    • 输入数据会存放到指定变量的地址中,因此需要使用 & 操作符传递变量地址,如 scanf("%d", &num);
  2. 使用 cin 输入
    • cin 会跳过空格字符(如空格、制表符、换行符等),并会在读取时处理回车符。
    • 读取输入时,可以直接将数据存放到变量中,如 cin >> num;
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值