I'm trying to grab the output from an ls command. How do I separate strings by the newline character? Currently my code looks like this:
let input = std::old_io::stdin().read_line().ok().expect("Failed to read line");
for c in input.chars() {
if c == '\n' {
break;
} else {
println!("{}", c);
}
}
This isn't working at all and I am printing all characters including \n.
Have a look at the lines method on BufRead. That function returns an iterator over all the lines of the buffer. You can get a BufRead from Stdin through the lock function. If you look at the documentation of lines you can see, that it will not return the newline char. Compare this to the read_line function which does return the newline char.
use std::io::BufRead;
fn main() {
// get stdin handle
let stdin = std::io::stdin();
// lock it
let lock = stdin.lock();
// iterate over all lines
for line in lock.lines() {
// iterate over the characters in the line
for c in line.unwrap().chars() {
println!("{}", c);
}
println!("next line");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With