-1

For this contrived rust code:

use std::io;

fn main() {
    println!("Enter the number:");

    let constant = "!";
    let mut guess = String::new();

    io::stdin().read_line(&mut guess)
        .expect("failed to readline");

    print!("You entered {}{}\n", guess, constant);
    print!("You entered {}{}\n", &guess[..1], constant);

}

the output is

Enter the number:
1
You entered 1
!
You entered 1!

and not

Enter the number:
1
You entered 1!
You entered 1!

Is rust adding extra special such as newline chars to the input string?

Junior Mayhé
  • 16,144
  • 26
  • 115
  • 161
  • 1
    After you entered the number 1, did you press Enter? – trent May 22 '20 at 19:56
  • Yes, that should be the case. It seems includes rust includes a newline in the returned string, as shared by another user https://stackoverflow.com/questions/27773313/why-does-my-string-not-match-when-reading-user-input-from-stdin. – Junior Mayhé May 22 '20 at 20:08

1 Answers1

2

The method that is ultimately called to read a line in this case is BufRead::read_line. That reads up to and including the newline delimiter, and places it in the buffer provided. So when you print guess, you are printing 1\n, then the ! character. The slice-then-print version does not include that trailing newline.

bnaecker
  • 6,152
  • 1
  • 20
  • 33
  • 1
    Of note: Ruby does the same, and presumably a lot of other languages do too. Ruby does a special method to trim the last character if it's a newline though. – John Dvorak May 22 '20 at 20:00