Println!() still created newline in "for loop"

I've been looking for the answer on internet, to print a few text without created newline, and found a solution using

io::stdout().flush().unwrap();

but it's seems doesn't work in "for loop".

use std::io;
use std::io::Write;


fn main() {
    let board: Vec<Vec<char>> = vec![
        vec!['-', '-', '-'],
        vec!['-', '-', '-'],
        vec!['-', '-', '-'],
    ];
    
    print_board(&board);
}


fn print_board(board: &Vec<Vec<char>>) {
    for row in board {
        for slot in row {
            println!("{}", slot);
            io::stdout().flush().expect("Something went wrong");
        };
    };
}

I think you want to use the print!() macro to print one slot on your board, then at the end of each row you can use println!() to print the newline character and flush to stdout.

fn main() {
    let board: Vec<Vec<char>> = vec![
        vec!['-', '-', '-'],
        vec!['-', '-', '-'],
        vec!['-', '-', '-'],
    ];

    print_board(&board);
}

fn print_board(board: &Vec<Vec<char>>) {
    for row in board {
        for slot in row {
            print!("{}", slot);
        }

        println!();
    }
}

(playground)

Running this code in the playground outputs the following:

---
---
---
3 Likes

println always prints a newline at the end, that’s what the "ln" part refers to (short for "line").

2 Likes

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.