Using Stdin::read_line
without trimming the newline character can cause runtime issues, especially when parsing the input into another
type (e.g., i32
). The operation will fail if the string contains a trailing newline character, making the code unreliable.
Code examples
Noncompliant code example
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read a line");
let num: i32 = input.parse().expect("Not a number!"); // Noncompliant: The input string may contain a newline character.
Compliant solution
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read a line");
let num: i32 = input.trim_end().parse().expect("Not a number!"); // Compliant: Trims the trailing newline character.