How to accept an input on one line with the text?

Hello! :slight_smile:
I have this code:

use std::io::stdin;

fn readln(s: &mut String) {
    stdin().read_line(s).unwrap();
}

fn pow(n: i32, p: i32) -> i32 {
    if p == 1 {
        return n;
    }

    n * pow(n, p - 1)
}

fn main() {
    let mut n = String::new();
    let mut p = String::new();

    println!("Enter the number:");
    readln(&mut n);

    println!("Enter the power:");
    readln(&mut p);

    let n = n.trim().parse().unwrap();
    let p = p.trim().parse().unwrap();

    let result = pow(n, p);

    println!("You entered '{}^{}' and this equals '{}'", n, p, result);
}

My input is 5 and 2, next output:

Enter the number:
5
Enter the power:
2
You entered '5^2' and this equals '25'

But how do I get my input to be on the same line as the text? print! does not help (it is visible only after input)

My expected output:

Enter the number: 5
Enter the power: 2
You entered '5^2' and this equals '25'

Thanks for help! :slight_smile:

You have to use the print! macro, then stdout.flush(). See the official docs of print! for a simple example.

3 Likes