C++输入输出全解

C++ 输入输出基础

C++ 的输入输出主要基于 <iostream> 库,使用 cincout 对象实现标准输入输出。

输入示例:

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++ 中大多数输入输出场景。根据需求选择合适的工具库和技巧。

相关推荐
拳里剑气4 小时前
C++算法:多源BFS
c++·算法·宽度优先·多源bfs
ysa0510305 小时前
【板子】短序列dp(换成维护更小常数维度的dp)
c++·笔记·算法·板子
aramae7 小时前
C++ IO流完全指南:从C标准库到C++流式编程
服务器·c语言·开发语言·c++·后端
_wyt0017 小时前
c++里的族谱:树
c++·
@三十一Y8 小时前
C++:AVL树实现
c++
haolin123.9 小时前
类和对象(上)
开发语言·c++
ShineWinsu9 小时前
对于Linux:传输层协议UDP原理的解析
linux·c++·面试·udp·协议·传输层·计算机系统
LingzhiPi9 小时前
零知派ESP32--AS5600磁吸旋钮音量控制器
c++·单片机·嵌入式硬件
小保CPP9 小时前
OpenCV C++车型识别1-图像预处理
c++·人工智能·opencv·计算机视觉
库克克9 小时前
【C++】C++11 包装器function 与 绑定器 bind
开发语言·c++