Last active
March 8, 2024 10:50
-
-
Save brendanashworth/121e9b886fe9bf737654 to your computer and use it in GitHub Desktop.
Rust: reading lines from STDIN and printing them back to console
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io; | |
fn main() { | |
// Iterate over the lines in io::stdin() | |
for line in io::stdin().lines() { | |
// Now print the line (line.unwrap() first) via the println!() macro | |
println!("{}", line.unwrap()); | |
} | |
} |
You need to import the prelude use std::io::prelude::*; and call stdin.lock().lines()
Thanks for this. Here is the whole main.rs that worked for me.
use std::{io, io::prelude::*};
pub type Error = Box<dyn std::error::Error + Send + Sync>;
pub type Result<T> = std::result::Result<T, Error>;
pub fn main() -> Result<()> {
for line in io::stdin().lock().lines() {
println!("length = {}", line?.len());
}
Ok(())
}
Thanks. This is almost what I was looking for.
So this works for me:
echo "hello" | cargo run
However, the following hangs forever until I enter some value
cargo run
Is there a way to have it stop if nothing was pipped into it?
Thanks. This is almost what I was looking for. So this works for me:
echo "hello" | cargo runHowever, the following hangs forever until I enter some value
cargo runIs there a way to have it stop if nothing was pipped into it?
It has nothing to do with rust but the program is not hanging it is listenings to standard input ( your keyboard) you can type things and to stop it listening you type ctrl-d.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same.