Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read string until newline

Tags:

rust

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.

like image 508
user3918985 Avatar asked Mar 23 '15 09:03

user3918985


1 Answers

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");
    }
}
like image 73
oli_obk Avatar answered Nov 15 '22 09:11

oli_obk