C++ 输入输出基础
C++ 的输入输出主要基于 <iostream> 库,使用 cin 和 cout 对象实现标准输入输出。
输入示例:
cpp
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter a number: ";
cin >> num; // 从用户输入读取整数
cout << "You entered: " << num;
return 0;
}
输出示例:
cpp
cout << "Hello, World!" << endl; // endl 用于换行
cout << "Value: " << 42; // 输出变量和常量
格式化输出
通过 <iomanip> 库控制输出格式,如宽度、精度、对齐等。
设置宽度和填充:
cpp
#include <iomanip>
cout << setw(10) << setfill('*') << 123; // 输出 "*******123"
控制浮点数精度:
cpp
double pi = 3.1415926535;
cout << fixed << setprecision(2) << pi; // 输出 "3.14"
文件输入输出
使用 <fstream> 库读写文件,需创建 ifstream(输入)或 ofstream(输出)对象。
写入文件:
cpp
#include <fstream>
ofstream outfile("example.txt");
outfile << "This is written to a file." << endl;
outfile.close();
读取文件:
cpp
ifstream infile("example.txt");
string line;
while (getline(infile, line)) {
cout << line << endl;
}
infile.close();
字符串流处理
通过 <sstream> 库实现字符串与变量的灵活转换。
字符串分割示例:
cpp
#include <sstream>
string data = "C++ Python Java";
istringstream iss(data);
string word;
while (iss >> word) {
cout << word << endl; // 逐词输出
}
数值转换:
cpp
string s = "123";
int x;
istringstream(s) >> x; // 字符串转整数
错误处理与输入验证
确保输入数据的有效性,避免程序崩溃。
检查输入是否有效:
cpp
int num;
cout << "Enter a number: ";
while (!(cin >> num)) {
cin.clear(); // 清除错误状态
cin.ignore(100, '\n'); // 忽略错误输入
cout << "Invalid input. Try again: ";
}
高级技巧:二进制 I/O
适用于非文本数据(如图片、结构体)。
二进制写入:
cpp
ofstream binfile("data.bin", ios::binary);
int arr[] = {1, 2, 3};
binfile.write(reinterpret_cast<char*>(arr), sizeof(arr));
binfile.close();
二进制读取:
cpp
ifstream binfile("data.bin", ios::binary);
int arr[3];
binfile.read(reinterpret_cast<char*>(arr), sizeof(arr));
binfile.close();
通过以上方法,可以覆盖 C++ 中大多数输入输出场景。根据需求选择合适的工具库和技巧。