-1

So I have a code which constantly asks for input and then executes your input as a shell command. I understand that the output I am getting from the shell commands is in a buffer of some sort. Now, however, as there are many commands which output lots of lines, I would like to get all of the output into one single string.

extern crate subprocess;

use std::io;
use std::io::{BufRead, BufReader};
use subprocess::Exec;

fn main() {
    loop {
        let mut mycommand_string: String = String::new();
        io::stdin()
            .read_line(&mut mycommand_string)
            .expect("Failed to read line");

        let mycommand: &str = &*mycommand_string;

        let x = Exec::shell(mycommand).stream_stdout().unwrap();
        let br = BufReader::new(x);

        let full: String = " ".to_string();

        let string = for (i, line) in br.lines().enumerate() {
            let string: String = line.unwrap().to_string();
            let full = format!("{}{}", full, string);
            println!("{}", full);
        };
        println!("{}", string);
    }

}

This is my code. As you can see, the thing I am aiming for is to somehow iterate over br.lines() and for each line of output it contains, append or concatenate it to a string, so that all the output ends up in one single string, preferably with "\n" in between each line, but not neccesarilly.

Specifically I would like to iterate over the result of the variable br which has a type I dont understand and to concatenate all the strings together.

franco
  • 1
  • 2
  • Welcome to Stack Overflow! It looks like your question might be answered by the answers of [Join iterator of &str](https://stackoverflow.com/q/56033289/155423); [What's an idiomatic way to print an iterator separated by spaces in Rust?](https://stackoverflow.com/q/36941851/155423); [How do I concatenate strings?](https://stackoverflow.com/q/30154541/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Feb 27 '22 at 13:25

1 Answers1

0

If you have an iterator of lines, then you can simply collect that into a string:

br.lines().collect();

Of course we should not ignore that there do not seem to be many possible reasons for ever doing that...

hkBst
  • 2,818
  • 10
  • 29