You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重载C++ >>运算符读取分号分隔的adress结构体文件数据

C++ 按分号分隔符重载流读取运算符实现

默认operator>>读取std::string时以空白字符为截断边界,会将分号及后续内容全部读取到street字段,导致后续num字段读取失败,可通过std::getline指定分隔符实现自定义拆分,修改后代码如下:

#include <istream>
#include <string>

std::istream &operator>> (std::istream &in, adress &adr)
{
    // 指定分号为分隔符读取street字段,自动丢弃分隔的分号
    std::getline(in, adr.street, ';');
    // 读取分号后的数字到num字段
    in >> adr.num;
    // 跳过当前行末尾的换行符,避免下次读取时getline读到空内容
    in.ignore();
    return in;
}

小提示:如果需要兼容Windows系统的\r\n换行符,或者行尾存在多余空白的场景,可以将in.ignore()替换为in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');,使用前需要引入<limits>头文件。

如果需要兼容读取失败的场景,符合流运算符的通用设计规范,可以增加状态判断,读取失败时不修改原结构体内容:

#include <istream>
#include <string>
#include <limits>

std::istream &operator>> (std::istream &in, adress &adr)
{
    std::string temp_street;
    int temp_num;
    // 仅当两个字段都读取成功时才赋值到目标结构体
    if (std::getline(in, temp_street, ';') && in >> temp_num) {
        adr.street = std::move(temp_street);
        adr.num = temp_num;
        in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
    return in;
}

内容的提问来源于stack exchange,提问作者Miha Demon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 20:09:04