rspec/rules/S7441/rust/rule.adoc
github-actions[bot] 314d4b0ed2
Create rule S7441: Lines read from the standard input should be trimmed (#4784)
* Create rule S7441

* Update RSPEC

---------

Co-authored-by: yassin-kammoun-sonarsource <yassin-kammoun-sonarsource@users.noreply.github.com>
Co-authored-by: yassin-kammoun-sonarsource <yassin.kammoun@sonarsource.com>
2025-03-19 13:06:36 +00:00

29 lines
1.0 KiB
Plaintext

== Why is this an issue?
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
[source,rust,diff-id=1,diff-type=noncompliant]
----
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
[source,rust,diff-id=1,diff-type=compliant]
----
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.
----
== Resources
=== Documentation
* Clippy Lints - https://rust-lang.github.io/rust-clippy/master/index.html#read_line_without_trim