Issue with reading from stdin

I've been working on a codeforces problem, when I hit a strange issue - the first read from stdin works fine, but the second one reads only a new-line (i.e. \n) and ignores the actual data.

The strange thing is that I failed to reproduce it with a simple reading in a loop, but it is 100% reproducible with my code (on my machine). Here is a minimal reproducible example:

use std::error::Error;
use std::io::{BufRead, Write};

fn main() -> Result<(), Box<dyn Error + Send + Sync>> {
    let stdin = std::io::stdin();
    let stdout = std::io::stdout();

    let mut input = stdin.lock();
    let mut output = stdout.lock();
    let mut buffer = String::with_capacity(64);

    input.read_line(&mut buffer)?;
    let _test_cases = buffer.trim().parse::<usize>()?;

    // writeln!(
    //     output,
    //     "When I uncomment this, it works, why ? >>> {}",
    //     _test_cases
    // )?;

    buffer.clear();
    input.read_line(&mut buffer)?;

    writeln!(output, "The buffer contains: {:?}", buffer)?;

    buffer
        .split(' ')
        .map(|x| x.trim())
        .filter(|x| !x.is_empty())
        .enumerate()
        .try_for_each::<_, Result<(), Box<dyn Error + Send + Sync>>>(|(idx, test_case)| {
            let tc = test_case.parse::<u32>()?;

            if idx > 0 {
                write!(output, " ")?;
            }

            write!(output, "{}", tc)?;

            Ok(())
        })?;

    output.flush()?;
    Ok(())
}

So why does it work when I uncomment the commented-out writeln!() and does not work otherwise ? Is this a bug in the standard library, or am I missing something fundamental ?

OS: Debian Sid
Rust: rustc 1.61.0 (fe5b13d68 2022-05-18)

I cannot reproduce this locally; it works as expected, independent of whether the output line is commented out or not.

I've been playing around with it and it might seem to be an issue with IntelliJ. I've been testing different terminals and get the issue only when launched from IJ.

Also ZSH does not seem to respect the last flush() and requires a writeln!() in order to display the last line, but that's another issue.

Thanks for trying it out :slight_smile:

Oh, yeah, IDEs are fun. This is one of the big reasons why I don't trust any IDE at all. The program's output from a regular (preferably system built-in) terminal is the ground truth. IDEs often try to outsmart and second-guess the user, which is immensely annoying exactly when one would need faithful output the most: while debugging.

A couple days ago I encountered a post by an annoyed user who seemed to outright lose some of the first characters of each output line. It turns out their Python IDE assumed that anything that starts with ... must be Python's continuation prompt and must therefore be suppressed. :man_shrugging: