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

本文共 1297 字,大约阅读时间需要 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/

    你可能感兴趣的文章
    python zipfile模块学习笔记(一)
    查看>>
    Python zip函数 详解(全)
    查看>>
    Python \r\n与\n的转换
    查看>>
    python __new__中单例的作用
    查看>>
    python | aiofiles,一个超酷的 Python 库!
    查看>>
    python | akshare,一个超强的 开源Python 金融数据接口库!
    查看>>
    python | alabaster,一个强大的 关于alabaster 主题 Python 库!
    查看>>
    python | algorithms,一个超赞的 集合常用算法的Python 库!
    查看>>
    python调用jpype 报错:OSError JVM is already started和JVM cannot be restarted
    查看>>
    python | authlib,一个强大的 Python 库!
    查看>>
    python | awswrangler,一个高效的 Python 库!
    查看>>
    python | bashplotlib,一个有趣的Python库!
    查看>>
    python | bentoml,一个超级厉害的 模型部署 Python 库!
    查看>>
    python调用jar包的模块_python调用jar包
    查看>>
    python | black,一个神奇的 代码格式化工具 Python 库!
    查看>>
    python | bleach,一个超强的 Python 库!
    查看>>
    python | cartopy,一个有趣的 Python 库!
    查看>>
    python | cloud-init,一个实用的 云计算 Python 库!
    查看>>
    python | code2flow,一个神奇的 Python 库!
    查看>>
    python | cudf,一个超实用的 Python 库!
    查看>>