user3918985
user3918985

Reputation: 4419

Read string until newline

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.

Upvotes: 6

Views: 6553

Answers (2)

Vladimir Matveev
Vladimir Matveev

Reputation: 127791

It is difficult to understand what you actually want from your explanation, but if you want to read every line from the input without a newline character you can use lines() iterator. The following is the version for the new std::io:

use std::io::BufRead;

let input = std::io::stdin();
for line in input.lock().lines() {
    // here line is a String without the trailing newline
}

Upvotes: 3

oli_obk
oli_obk

Reputation: 31193

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");
    }
}

Upvotes: 6

Related Questions