I'm trying to parse a vector of strings that are all the same length into a vector of integers (usize in this case).
When I loop through the original string containing all numbers separated by "\n", it works and returns a vector of strings that are all the same length. However, when I iterate over that Vec of Strings and parse it to a Vec of usize, the numbers change lengths.
Here's my code:
fn read_input() -> String {
let mut input = String::new();
File::open("input.txt").unwrap().read_to_string(&mut input).unwrap();
let test: Vec<&str> = input.split("\n").collect();
let test2: Vec<usize> = test.iter().map(|n| n.parse().unwrap()).collect();
for num in test2{
println!("{}", num);
}
return input;
}
Here's a sample of what it should look like:
100101000011
100101001010
111001001011
010110011110
111111010111
111000000111
101000101100
000000101100
111010001010
000000001110
011001111101
000000111010
010001000001
Here's a sample of how it looks like right now:
110110110110
10111101100
10000101100
1110001110
11000010001
1101010000
100111111111
101110010111
1101100100
1000010010
10000000011
110000010
1101000
NOTE: The full list has about 2000 entries, and the output is correct for the most part, but there are a few sections where the numbers get trimmed for some reason.
CodePudding user response:
Numbers aren't changed. They're numbers, there's no intrinsic 0
at the start: those are dependent on how you print them.
If you want them to have a padding with 0
, change the print call:
for num in test2{
println!("{:012}", num);
}
In your case, the numbers are parsed from binary and should be printed as binary. So you want
for num in test2{
println!("{:012b}", num);
}