String converted to integer adds empty line?

Hi there, im new to rust and experimenting with a few things. I wrote a program which gets your input (string) and converts it to an int. After that it prints the original string and the converted integer value in the same print!.

here is my code:

use std::io;

fn main() {

let y=3;

let mut input = String::new();

io::stdin() // the rough equivalent of `std::cin`

.read_line(&mut input) // actually read the line

.expect("Failed to read line"); // which can fail, however

let x: i32 = input

.trim() // ignore whitespace around input

.parse() // convert to integers

.expect("Input not an integer"); // which, again, can fail

println!("xxx");

print!("{}x{} ",input,x);

}

The expected outcome when entering eg. "3" would be:

3 (from input)
xxx
3x3

However the output really is:

3(from input)
xxx
3
x3

Thats why I added the variable y in my code and replaced "input" in the last print!. Now the output fitted my expectation. My assumption is, that when converting a string to a int there somehow is an empty line added to the string is that correct? Can you tell me how/why this happens?

trim returns a substring with the whitespace removed, it doesn't remove the whitespace from the string you call the method on. If you assign input.trim() to a variable and use that instead of input I think you'll get what you're expecting.

trim is actually a method on str[1] so it doesn't have access to the mutable storage to remove characters from your String in the first place.


  1. str methods can still be called on String because it implements Deref<Target = str> ↩ī¸Ž

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.