Hello everyone, greetings.
I'm new to rust and I don't know how data entry works here, could someone explain to me what its syntax is and how it works?
I'm new to rust and I don't know how data entry works here, could someone explain to me what its syntax is and how it works?
If you want to take input from the standard input stream, here is how to do it in code:
use std::io;
fn main() {
let mut input: String = String::new(); // Create a string variable
io::stdin() // Get the standard input stream
.read_line(&mut input) // The read_line function reads data until it reaches a '\n' character
.expect("Unable to read Stdin"); // In case the read operation fails, it panics with the given message
println!("You entered: {}", input);
}
Tips for fixing or avoiding some common beginner problems:
read_line
will append to the string you provide, rather than overwriting it. You will typically want to pass it a new empty string, or call .clear()
on an existing string before re-using it.read_line
will include any carriage-return / newline characters that it reads. You will typically want to call trim
on the resulting string before using it.parse
method to convert the input string into a number or other type. (Remember to call .trim()
before .parse()
to avoid errors!)Putting a few tricks together for a common type of program where you read commands in a loop:
for line in std::io::stdin().lines() {
let mut args = line.split();
match args.next() {
None => continue,
Some("get") => {
let name = args.next();
// ...
}
// ...
Some(command) => {
println!("Unknown command: {command}");
}
}
}
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.