C++输入输出全解

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

相关推荐
丰色木夕6 小时前
Ubuntu22.04下源码编译安装USD-Brep
c++·ubuntu·nvidia·usd-brep
衍玊9 小时前
多路转接原理与应用
c++
himobrinehacken10 小时前
位运算揭秘:左右移与符号位陷阱
c语言·c++·算法·安全
Android小码家13 小时前
Vehicle 实战 自定义属性+测试demo
java·c++·framework·vhal·vehicle
hetao173383713 小时前
2026-10-19 hetao1733837 的刷题记录
c++·算法
夏虫不可与之言冰13 小时前
第三课 点亮 LED 与定时器非阻塞闪烁
c语言·c++·vscode·单片机·嵌入式硬件·物联网
辛苦才能14 小时前
C++ 哈希表深度解析:删除为什么必须打标记,负载因子为什么卡 0.7
开发语言·数据结构·c++·算法
miller-tsunami14 小时前
STL简介&string相关知识点
开发语言·c++·string
坤坤子吖14 小时前
Linux 线程同步与互斥——互斥锁
linux·服务器·c++·笔记·学习
TDTC_XQ14 小时前
Linux网络编程accept的讲解
linux·服务器·c++