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

相关推荐
Keven_118 小时前
算法札记:ACM适用的很骚的C++语法(持续更新)
开发语言·c++
mengzhi啊8 小时前
QPluginLoader 动态 DLL 插件版,支持插件之间通信,广播。请求和应答
c++·qt
老赵的博客11 小时前
c++ QT之动态库加载问题
c++·qt
(Charon)11 小时前
【C++】定时器进阶:使用最小堆管理定时任务
c++·算法
hansang_IR11 小时前
【题解】 [省选联考 2021 A/B 卷] 卡牌游戏
c++·算法
lzx_00212 小时前
C++11(一)
开发语言·c++·算法
小七在进步13 小时前
C++入门(2)
java·jvm·c++
en.en..14 小时前
C语言核心解析:#define与typedef本质区别
开发语言·c++·算法
码匠许师傅14 小时前
【设计模式精讲】26.策略模式(Strategy)
c++·设计模式·策略模式·uml
果果燕15 小时前
实习笔记(六)主机按钮状态上报完整流程
开发语言·c++·php