

How can I read a single line from stdin?
source link: https://stackoverflow.com/questions/30186037/how-can-i-read-a-single-line-from-stdin
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Join Stack Overflow to learn, share knowledge, and build your career.
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",...)
.
In How to read user input in Rust? you can see how to iterate over all lines:
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
for line in stdin.lock().lines() {
println!("{}", line.unwrap());
}
}
You can also manually iterate without a for-loop:
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let mut iterator = stdin.lock().lines();
let line1 = iterator.next().unwrap().unwrap();
let line2 = iterator.next().unwrap().unwrap();
}
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?):
use std::io::{self, BufRead};
fn main() {
let stdin = io::stdin();
let line1 = stdin.lock().lines().next().unwrap().unwrap();
}
You can also use the text_io
crate for super simple input:
#[macro_use] extern crate text_io;
fn main() {
// reads until a \n is encountered
let line: String = read!("{}\n");
}
If you truly want the equivalent to fgets
, then @Gerstmann is right, you should use Stdin::read_line
. This method accepts a buffer that you have more control of to put the string into:
use std::io::{self, BufRead};
fn main() {
let mut line = String::new();
let stdin = io::stdin();
stdin.lock().read_line(&mut line).unwrap();
println!("{}", line)
}
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.
Read a single line from stdin
:
let mut line = String::new();
std::io::stdin().read_line(&mut line)?; // including '\n'
You may remove '\n'
using line.trim_end()
Read until EOF:
let mut buffer = String::new();
std::io::stdin().read_to_string(&mut buffer)?;
Using implicit synchronization:
use std::io;
fn main() -> io::Result<()> {
let mut line = String::new();
io::stdin().read_line(&mut line)?;
println!("You entered: {}", line);
Ok(())
}
Using explicit synchronization:
use std::io::{self, BufRead};
fn main() -> io::Result<()> {
let stdin = io::stdin();
let mut handle = stdin.lock();
let mut line = String::new();
handle.read_line(&mut line)?;
println!("You entered: {}", line);
Ok(())
}
If you interested in the number of bytes e.g. n
, use:let n = handle.read_line(&mut line)?;
orlet n = io::stdin().read_line(&mut line)?;
Try this:
use std::io;
fn main() -> io::Result<()> {
let mut line = String::new();
let n = io::stdin().read_line(&mut line)?;
println!("{} bytes read", n);
println!("You entered: {}", line);
Ok(())
}
See doc
Your Answer
Post as a guest
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged rust or ask your own question.
Recommend
-
55
In this post I want to discuss faking (or redirecting ) standard input and output ( os.Stdin and os.Stdout ) in Go programs. This is often done in tests, but may also be useful in other scenarios. ...
-
21
2019-02-10IntroductionWhen I wrote my last two tools multicode and epoch, I wanted them to work with...
-
29
Read a file (stdin) line by line yourbasic.org/golang Read from file Use a
-
30
Introduction Among the popular operating systems, they have all standardized on using standard input, standard output, and standard error with file desciptors 0, 1, and 2 respectively. This allows you to pipe the inputs and outputs...
-
28
Introduction Operating systems recognize a couple special file descriptor IDs: STDIN - 0 - Input usally coming in from keyboard. STDOUT - 1 - Output from the...
-
20
让ssh从stdin读取密码 执行像ssh,scp这类secure command时,必须手工输入密码,而且它们是直接从/dev/tty而不是stdin中读取密码的,这也意味着无法通过重定向IO的方式传送密码給这些程序. 查了一下网上一般的解决方案是借助 paramiko
-
22
Eclipse reading stdin (System.in) from a file advertisements Is it possible for Eclipse to read stdin from a file? Pure Ja...
-
15
Copy link Contributor Patrick-Poitras ...
-
16
In this Python tutorial, you will learn how do you read the input from stdin. Table Of Contents Let’s dive into the tutorial. Read input from stdin using sys.stdin
-
10
include <bits/stdc++.h>using namespace std;int number; int l1,r1,l2,r2;int main(){ cin >> number; for(int i = 0; i < number; i++){ cin >> l1 >> r1 >> l2 >> r2; //basically, check if...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK