Skip to content

Instantly share code, notes, and snippets.

@brendanashworth
Last active March 8, 2024 10:50
Show Gist options
  • Save brendanashworth/121e9b886fe9bf737654 to your computer and use it in GitHub Desktop.
Save brendanashworth/121e9b886fe9bf737654 to your computer and use it in GitHub Desktop.
Rust: reading lines from STDIN and printing them back to console
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());
}
}
@ctaggart
Copy link

ctaggart commented Aug 8, 2020

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(())
}

@ismet55555
Copy link

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?

@ergre314
Copy link

ergre314 commented Mar 8, 2024

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?

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