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)