【问题标题】:ParseIntError when parsing text file with comma-delimited data?解析带有逗号分隔数据的文本文件时出现 ParseIntError?
【发布时间】:2019-12-04 03:19:08
【问题描述】:

我在解析 rust 中的逗号分隔数据时遇到问题。有什么想法吗?

文本文件如下,

1,2,3,4,5,6

我尝试用以下失败来解析它。

    let contents: String = fs::read_to_string("data.txt").expect("Unable to open file");
    let opcodes: Vec<i32> = contents.split(",").map(|x| x.parse::<i32>().unwrap()).collect();

我已经修改了上面的内容,为每个解析打印x,看起来拆分的结果看起来像是在 map 中用作 ["1","2","3","4"," 5","6",""]。

解决方案:

read_to_string 似乎添加了一个尾随换行符。在split 之前添加对trim 的调用可以解决此问题。

let opcodes: Vec<i32> = contents.trim().split(",").map(|x| x.parse::<i32>().unwrap()).collect();

【问题讨论】:

    标签: rust


    【解决方案1】:

    你自己回答了。 read_to_string 不会随意添加换行符。仅当基础文件包含换行符时,结果字符串才包含换行符。

    要检查data.txt 中有多少换行符,请执行此操作

    cat -t -e data.txt
    # you will see meta characters at the end of each line.
    

    【讨论】:

      猜你喜欢
      • 2013-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-18
      • 1970-01-01
      • 2017-02-03
      • 2016-06-22
      • 2019-01-22
      相关资源
      最近更新 更多