+ 2
[SOLVED] Rust if else and user input
Where did i wrong here use std::io; fn main() { println!("Welcome to Guessing number game"); println!("Would you like to start the game? (y/n)"); let mut is_start = String::new(); io::stdin() .read_line(&mut is_start) .expect("Failed to read line."); if is_start == "y" { println!("Please input your guess"); } else if is_start == "n" { println!("Successfully quit the game"); println!("If you want to start game again, please restart your terminal"); } else { println!("Invalid command"); }; } When i type y it's not print "Please input your guess" and instead print "Invalid command"
11 Antworten
+ 2
Your input coming from the keyboard will contain the trailing newline character. Before comparing you have to remove that character.
For example:
1)
let is_start = is_start.trim_end();
You need the let because trim_end() will return a different data type.
2)
is_start.truncate(1);
This cuts the length down to one. Disadvantage: it will accept y, yes, yeppediddlidooah, ... everything that start with a y (other letters accordingly)
3)
is_start.truncate(is.start.len()-1);
This chops off the last character. May cause problems on other OSes that use more than a \n to end a line.
+ 2
Ani Jona 🕊 use your first method, and now it's working. thanks
+ 2
Your "n" part is not a single expression, wrap it in curlies { }
+ 1
Sure, you can use a match expression.
+ 1
I would not expect that much of a difference, let alone any significance! But generally, a match I would expect to be more efficient because it avoids a repeated comparison.
+ 1
Thanks for your help man Ani Jona 🕊
+ 1
You're welcome :)
0
And one more thing
0
Can i do above checking without if else in rust?
0
Which one is more efficient is rust match expression or if else above?
0
match is_start {
"y" => println!("Please input your guess"),
"n" => println!("Successfully quit the game") println!("If you want to start game again, please restart your terminal"),
_ => println!("Invalid command")
};
Why when i do this it give me an error?