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
输出时也会在缓冲区满或者遇到换行符时刷新输出。
注意事项
- 使用
scanf
输入- 需要使用格式化字符指定输入数据类型,如
%d
表示整数,%f
表示浮点数,%s
表示字符串等。 - 输入数据会存放到指定变量的地址中,因此需要使用
&
操作符传递变量地址,如scanf("%d", &num);
。
- 需要使用格式化字符指定输入数据类型,如
- 使用
cin
输入cin
会跳过空格字符(如空格、制表符、换行符等),并会在读取时处理回车符。- 读取输入时,可以直接将数据存放到变量中,如
cin >> num;
。