Issue related to use of break statement with Ok variant

hello dear group members hope this message finds you well i am trying to write a code in which i want to take input(no of players in game) from user and parse it in integer form my code is placed below. i have placed code for user input in loop and i have used match statement and i want that if user input wrong number of player(like if user input no of players = six) it will again asked for user input and if user input correct number like (no of players = 6) then it will break and return that number to number_of_players variable. issue is when i used break statement in arm of match with ( OK variant ) it will not execute i think the syntax is not right.1 more thing i want to make code dynamic i.e if user input no of players=3 then it will also asked for name of 3 players and if user input no of players=10 then it will also asked for name of 10 players how can i do this. any help in this regard. sorry for bothering you all i am new to programming and trying to make different codes. please anyone can help me in this regard.

use rand::Rng;
use std::io;
fn main() {
    let num = rand::thread_rng().gen_range(1, 6);
    println!("{}", num);

let mut number_of_players=String::new();
loop{

    println!("enter the no of players");

    io::stdin().read_line(&mut number_of_players);

let number_of_players:u32= match number_of_players.trim().parse(){

    Ok(number)=>{break;

               number }, 

    Err(_)=>{println!("please enter correct no of players");

                continue}

};

}

//println!("after returning from parse:{}", number_of_players);

}

Could you please format the post according to Forum Code Formatting and Syntax Highlighting?

brother now it's correct?

Much better :slight_smile: although I don't understand why the code is broken into parts...

The break statement breaks out of the loop, number after break has no effect, since the execution will resume at the end of the loop (and then exists).
You may want to create a function that gets the player count:

use std::io;

fn get_num_players() -> u32 {
    let mut number_of_players = String::new();

    loop {
        println!("enter the no of players");

        io::stdin().read_line(&mut number_of_players);
        match number_of_players.trim().parse() {
            Ok(number) => return number,
            _ => println!("please enter correct no of players"),
        }
    }    
}

fn main() {
    let players = get_num_players();
    println!("{} players", players);
}
1 Like

brother thanks for your time and support but u dont understand my question is if user input correct number of players than at that point compiler will come out of loop that's why i want to use break statement to break where user input correct number of players. here loop didn't stop even u enter correct number of player

brother can u guide me in this context

You should probably provide an updated version of your code. The one in the OP breaks no matter what number you enter so it sounds you're running something different now, and it's hard to say what the problem is without seeing the code.

1 Like

thanks for your reply i just want that user input number of players if it is right the loop terminates and if it is wrong it will ask again to input correct number of player. the code i pasted above didn't stop even after user input correct number of player. that's why i am asking help.

The code runs fine on my machine:

4
enter the no of players
6

Are you sure you input successfully? Change

io::stdin().read_line(&mut number_of_players);

to

io::stdin()
    .read_line(&mut number_of_players)
    .expect("cannot read line");

to see if the code is able to receive your input.


Apart from that, here's two more suggestions for your code:

  • Use rustfmt to format your code properly.

  • The last number here is unreachable and can be removed:

    Ok(number) => {
        break;
        number
    }
    

    The first number can also be replaced by _.

I found these suggestions with clippy.

thanks your kind reply but it didn't terminate the loop even after input of correct number of player. i want that it should terminate the loop and execute the remaining code. but as output shows it goes on asking for input number of player again and again

i have done this with little changes in code

use std::io;
use rand::Rng;
use std::collections::HashMap;
fn main() {
    let number_of_players:u8;// number of players who will play game
    loop {
        println!("Please input no of player.");

        let mut guess = String::new();

 io::stdin().read_line(&mut guess).expect("Fail to read line");
     
 let   guess: u8 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => {println!("enter correct no of players");
                        continue}
        };
 
        number_of_players=guess;
        break;
    }
 
    println!("no of player is:{}",number_of_players);

}

now if i enter wrong number of player it will again ask for correct no of players and when correct no of players enter it will stop. output is shown below:

Please input no of player.
six
enter correct no of players
Please input no of player.
four
enter correct no of players
Please input no of player.
4
no of player is:4

can u help me i want to enter the name of players as well but frankly speaking i have no idea in my mind how can i do this.

Good! The code is already getting a bit long, so let's extract the part for reading the number of players into a function as @naim mentioned:

Now you can simply use get_num_players() to ask for the number of players.

To keep track of the names of players, we need to store the names in a Vec, which contains a dynamic sequence of elements, by using a loop to push strings into the Vec:

fn get_names(count: usize) -> Vec<String> {
    println!("Enter the names of players: ");

    let mut names = vec![];
    for _ in 0..count {
        let mut name = String::new();
        io::stdin().read_line(&mut name).expect("cannot read line");
        names.push(name);
    }
    names
}

You can also use a more advanced approach:

use std::io::prelude::*;

fn get_names(count: usize) -> Vec<String> {
    println!("Enter the names of players: ");
    io::stdin()
        .lock()
        .lines()
        .take(count)
        .collect::<Result<_, _>>()
        .expect("cannot read line")
}

If you change the return type of get_num_players to usize, then here's an example main function:

fn main() {
    let n = get_num_players();
    let names = get_names(n);

    println!("{:?}", names);
}
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.