Line read from standard input is used without trimming

ID

rust.correctness.lines_read_standard_input_trimmed

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Api Misuse

Language

Rust

Description

Detects a String filled by Stdin::read_line that is then parsed with parse or compared against a string literal in the same function, with no trim applied to it first.

Rationale

read_line appends the line terminator to the buffer, so the value still carries a trailing \n (and \r\n on Windows). "42\n".parse::<i32>() returns Err(InvalidDigit) and line == "quit" is false for the user who typed quit, so the program rejects perfectly valid input, usually only on one platform.

The following code illustrates the pattern detected by this rule:

use std::fs::File;
use std::io::{self, BufRead, BufReader};
fn read_count() -> i32 {
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    // FLAGGED: Line read from standard input is used without trimming
    let n: i32 = line.parse().unwrap();
    n
}

Remediation

Call trim() on the buffer before using it — line.trim().parse::<i32>() — or trim_end_matches(['\r', '\n']) when only the terminator should go. Reading with BufRead::lines() instead strips the terminator for you.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved