在C++中,输入和输出(I/O)主要通过标准库中的输入输出流来实现。以下是详细介绍:
1 标准输入输出流
C++标准库提供了iostream
头文件,其中包含了cin
和cout
这两个标准输入输出流对象,分别用于从标准输入设备(通常是键盘)读取数据和向标准输出设备(通常是屏幕)输出数据。
1.1 标准输出流(cout)
cout
是用于标准输出的流对象,通常连接到显示屏。使用流插入运算符<<
将数据输出到cout
:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!" << endl;
return 0;
}
1.2 标准输入流(cin)
cin
是用于标准输入的流对象,通常连接到键盘。使用流提取运算符>>
从cin
中读取数据:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter your age: ";
cin >> age;
cout << "Your age is: " << age << endl;
return 0;
}
2 标准错误流(cerr)
cerr
是用于输出错误消息的流对象,非缓冲,输出立即显示:
#include <iostream>
using namespace std;
int main() {
cerr << "Error: Something went wrong!" << endl;
return 0;
}
3 标准日志流(clog)
clog
是用于输出日志消息的流对象,缓冲输出:
#include <iostream>
using namespace std;
int main() {
clog << "Log: This is a log message." << endl;
return 0;
}
4 文件输入输出
C++还提供了fstream
库,用于文件的输入和输出操作:
4.1 文件输出
#include <fstream>
using namespace std;
int main() {
ofstream outFile("example.txt");
outFile << "Writing to a file." << endl;
outFile.close();
return 0;
}
4.2 文件输入
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream inFile("example.txt");
string content;
while (inFile >> content) {
cout << "Read from file: " << content << endl;
}
inFile.close();
return 0;
}
5 格式化输出
C++支持格式化输出,可以使用iomanip
库中的函数来设置输出格式。例如,使用setw
设置字段宽度,使用setprecision
设置浮点数的精度:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double pi = 3.141592653589793;
cout << "Default precision: " << pi << endl;
cout << "Fixed precision: " << fixed << setprecision(4) << pi << endl;
cout << "Scientific notation: " << scientific << pi << endl;
return 0;
}
6 兼容C语言的输入输出
C++兼容C语言的输入输出函数,例如printf
和scanf
:
#include <cstdio>
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("You entered: %d\n", num);
return 0;
}