I'm asking for the equivalent of fgets()
in C.
let line = ...;
println!("You entered: {}", line);
I've read How to read user input in Rust?, but it asks how to read multiple lines; I want only one line.
I also read How do I read a single String from standard input?, but I'm not sure if it behaves like fgets()
or sscanf("%s",...)
.
If you truly want the equivalent to
fgets
, then @Gerstmann is right, you should useStdin::read_line
. This method accepts a buffer that you have more control of to put the string into:Unlike C, you can't accidentally overrun the buffer; it will be automatically resized if the input string is too big.
The answer from @oli_obk - ker is the idiomatic solution you will see most of the time. In it, the string is managed for you, and the interface is much cleaner.
In How to read user input in Rust? you can see how to iterate over all lines:
You can also manually iterate without a for-loop:
You cannot write a one-liner to do what you want. But the following reads a single line (and is exactly the same answer as in How do I read a single String from standard input?):
You can also use the
text_io
crate for super simple input:Read a single line from
stdin
:You may remove
'\n'
usingline.trim_end()
Read until EOF:
Using implicit synchronization:
Using explicit synchronization:
If you interested in the number of bytes e.g.
n
, use:let n = handle.read_line(&mut line)?;
or
let n = io::stdin().read_line(&mut line)?;
Try this:
See doc