博客
关于我
C++:while(getline())函数
阅读量:486 次
发布时间:2019-03-06

本文共 1331 字,大约阅读时间需要 4 分钟。

在处理文件记录时,正确使用 getline() 函数可以确保逐行读取记录。以下是优化后的步骤:

  • 使用逐行读取:使用 getline(dataFile, input) 读取完整的记录直到换行符结尾。

    string input;
    while (getline(dataFile, input)) {
    // 处理每一行的输入
    }
  • 处理字段分隔符:在每一行中,使用 find('$') 找到 $ 符号的位置,分割字段:

    string name = input.substr(0, pos);
    input.erase(0, pos + 1); // 迷惑符保留
    string address = input.substr(0, next_pos);
    input.erase(0, next_pos + 1); // 保留下一个 $ 符号

    注意:确保 pos 和下一个 $ 符号的位置正确,以被分割。

  • 处理后续字段:继续找到下一个 $ 符号来分割城市等信息。

  • 处理换行符:在逐行读取时,确保 dataFile.get() 读取留下的换行符,以防止缓冲区溢出。

  • 示例代码

    #include 
    #include
    #include
    using namespace std;
    int main() {
    string input;
    fstream dataFile("addresses.txt", ios::in);
    if (!dataFile.is_open()) {
    cout << "Error opening file." << endl;
    return 0;
    }
    while (getline(dataFile, input)) {
    // 处理每一行
    size_t pos = input.find('$');
    if (pos == string::npos) break;
    string name = input.substr(0, pos);
    input.erase(0, pos + 1); // 舍弃第一个 $, 保留记录中的其他 $
    size_t next_pos = input.find('$', pos + 2);
    if (next_pos == string::npos) {
    cout << name << " '" << address << "'..." << endl;
    } else {
    // 读取后续字段
    address = input.substr(pos + 2, next_pos - (pos + 2));
    // 继续处理更多字段
    // ...
    }
    }
    dataFile.close();
    return 0;
    }

    注意事项

    • 每读取一个完整记录后,循环自动移动到下一行。
    • 保留 $ 符号用于内部字段分隔。
    • 确保处理多个 $ 符号才能分割所有字段。

    通过这种方法,可以正确处理每行记录,并提取相应的字段信息。

    转载地址:http://wemdz.baihongyu.com/

    你可能感兴趣的文章
    Nginx 反向代理 MinIO 及 ruoyi-vue-pro 配置 MinIO 详解
    查看>>
    nginx 反向代理 转发请求时,有时好有时没反应,产生原因及解决
    查看>>
    Nginx 反向代理解决跨域问题
    查看>>
    Nginx 反向代理配置去除前缀
    查看>>
    nginx 后端获取真实ip
    查看>>
    Nginx 学习总结(16)—— 动静分离、压缩、缓存、黑白名单、性能等内容温习
    查看>>
    Nginx 学习总结(17)—— 8 个免费开源 Nginx 管理系统,轻松管理 Nginx 站点配置
    查看>>
    Nginx 常用配置清单
    查看>>
    nginx 常用配置记录
    查看>>
    Nginx 我们必须知道的那些事
    查看>>
    Nginx 的 proxy_pass 使用简介
    查看>>
    Nginx 的配置文件中的 keepalive 介绍
    查看>>
    Nginx 负载均衡与权重配置解析
    查看>>
    Nginx 负载均衡详解
    查看>>
    nginx 配置 单页面应用的解决方案
    查看>>
    nginx 配置https(一)—— 自签名证书
    查看>>
    nginx 配置~~~本身就是一个静态资源的服务器
    查看>>
    Nginx 配置解析:从基础到高级应用指南
    查看>>
    Nginx下配置codeigniter框架方法
    查看>>
    nginx报错:the “ssl“ parameter requires ngx_http_ssl_module in /usr/local/nginx/conf/nginx.conf:128
    查看>>