1

I came across this anomalous behavior during printing:

use std::io;

fn main() {
    let mut number = String::new();
    io::stdin()
        .read_line(&mut number)
        .expect("Failed to read line");

    let mut number_len = number.len();
    number.truncate(number_len - 1); // removing trailing \n
    number_len = number.len();

    println!("Number entered is {} with length {}", number, number_len);

    for i in 0..(number_len - 1) {
        println!("Char at {} is {}", i, &number[i..i + 1]);
    }
}

Output

4200                                       <- my input
 with length 5 is 4200                     <- Oddly printed output
Char at 0 is 4
Char at 1 is 2
Char at 2 is 0
Char at 3 is 0

Why is this happening?

Additionally, the length of number is wrong... it should be 4 whereas it is printing 5 even after the truncating.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Ashniu123
  • 347
  • 4
  • 13
  • Possible duplicate: https://stackoverflow.com/q/27773313/1233251 – E_net4 Feb 26 '18 at 19:32
  • 2
    You are on Windows, where newlines are `\r\n` (not just `\n`). By removing a single character, you've left the `\r`, which is why the beginning part of your line is missing ("Number entered is"). Use `trim` instead. You can use the length of the trimmed string as the parameter to `truncate`, if you'd like. – Shepmaster Feb 26 '18 at 19:44

0 Answers0