gpt4 book ai didi

c++ - 流 >> 读取最后一行两次

转载 作者:太空宇宙 更新时间:2023-11-04 16:18:15 25 4
gpt4 key购买 nike

我正在尝试解析 /proc/partitions 文件。

major minor  #blocks  name

8 0 976762584 sda
8 1 99998720 sda1
8 2 1 sda2
8 3 103561216 sda3
8 4 291514368 sda4
8 5 1998848 sda5

这是我机器中的/proc/partitions 文件。

#include <boost/cstdint.hpp>
#include <fstream>
#include <boost/algorithm/string/trim.hpp>
#include <boost/format.hpp>

int main(){
std::ifstream proc_partitions_stream("/proc/partitions");
boost::int32_t disc_partition_line_count = -2; //-1 for headers, -1 for the empty line
//so counter is 0 when it tries to read the real entries
while(!proc_partitions_stream.fail()){
if(disc_partition_line_count >= 0){
boost::uint16_t major, minor;
boost::uint64_t blocks;
std::string label;
proc_partitions_stream >> major >> minor >> blocks >> label;
std::cout << boost::format("%1% %2% %3% %4%") % major % minor % blocks % label << std::endl;
boost::algorithm::trim(label);
}else{
std::string line;
std::getline(proc_partitions_stream, line);
}
++disc_partition_line_count;
}
return 0;
}

但是它读取最后一行两次这是程序

8 0 976762584 [sda]
8 1 99998720 [sda1]
8 2 1 [sda2]
8 3 103561216 [sda3]
8 4 291514368 [sda4]
8 5 1998848 [sda5]
8 5 1998848 [] << read the last line TWICE but didn't read the label

最佳答案

因为你的 while 循环条件是错误的,你在阅读之前测试失败,你应该在阅读之后测试失败。更好的方法是测试 getline 的返回值。

关于c++ - 流 >> 读取最后一行两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20142154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com