Read unknown number of lines

I want to read an unknown number of lines from users until they press ctrl+c. How do I do this?
Usually, there is an input for number of lines they enter but for this case, there is no such input, theyend with ctrl c.

use std::io;

fn main() {
    loop {
        let mut read_string = String::new();
        io::stdin()
            .read_line(&mut read_string)
            .expect("io read error");
        match read_string.trim().parse::<isize>() {
            Ok(v) => {
                println!("I've got the number {}", v)
            }
            Err(_) => {
                println!("Not a valid number")
            }
        }
    }
}

I am not sure if this is what you want

@Dennis-Zhang Please follow the syntax and formatting guidelines: Forum Code Formatting and Syntax Highlighting

Ctrl-C is a weird combination to use for end-of-input, because it usually means "terminate the program". End-of-input is instead signaled by Ctrl-D, which sends an EOF to the process, so if you use that, you can then just read until EOF:

use std::io::{ stdin, BufRead };

fn main() {
    let mut lines = Vec::new();
    let input = stdin();
    let mut stream = input.lock();
    
    let mut line = String::new();
    
    while let Ok(n) = stream.read_line(&mut line) {
        if n == 0 {
            break;
        }
        
        lines.push(line);
        line = String::new();
    }
    
    println!("{:#?}", lines);
}

If you do insist on using Ctrl-C, then you will need to install a signal handler, using an external crate, e.g. ctrlc or signal-hook. That is not trivial, because you have to terminate your input loop from a different, signal callback function. I think you could use a mutable bool flag, captured and modified from the signal handler function, but it's not pretty, and for UX reasons, it would be more idiomatic to go with Ctrl-D anyway.

5 Likes

Thank you. I had confused ctrl d with ctrl c, my mistake.

sorry, I am new to commuity, I have corrected it

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.