读取字符串直到换行
Read string until newline
我正在尝试获取 ls 命令的输出。如何用换行符分隔字符串?目前我的代码如下所示:
let input = std::old_io::stdin().read_line().ok().expect("Failed to read line");
for c in input.chars() {
if c == '\n' {
break;
} else {
println!("{}", c);
}
}
这根本不起作用,我正在打印所有字符,包括 \n。
通过lock
函数查看lines
method on BufRead
. That function returns an iterator over all the lines of the buffer. You can get a BufRead
from Stdin
。如果您查看 lines
的文档,您会发现它不会 return 换行符。将此与执行 return 换行符的 read_line
函数进行比较。
use std::io::BufRead;
fn main() {
// get stdin handle
let stdin = std::io::stdin();
// lock it
let lock = stdin.lock();
// iterate over all lines
for line in lock.lines() {
// iterate over the characters in the line
for c in line.unwrap().chars() {
println!("{}", c);
}
println!("next line");
}
}
很难从你的解释中理解你真正想要的,但如果你想从输入中读取没有换行符的每一行,你可以使用 lines()
迭代器。以下是新 std::io
的版本:
use std::io::BufRead;
let input = std::io::stdin();
for line in input.lock().lines() {
// here line is a String without the trailing newline
}
我正在尝试获取 ls 命令的输出。如何用换行符分隔字符串?目前我的代码如下所示:
let input = std::old_io::stdin().read_line().ok().expect("Failed to read line");
for c in input.chars() {
if c == '\n' {
break;
} else {
println!("{}", c);
}
}
这根本不起作用,我正在打印所有字符,包括 \n。
通过lock
函数查看lines
method on BufRead
. That function returns an iterator over all the lines of the buffer. You can get a BufRead
from Stdin
。如果您查看 lines
的文档,您会发现它不会 return 换行符。将此与执行 return 换行符的 read_line
函数进行比较。
use std::io::BufRead;
fn main() {
// get stdin handle
let stdin = std::io::stdin();
// lock it
let lock = stdin.lock();
// iterate over all lines
for line in lock.lines() {
// iterate over the characters in the line
for c in line.unwrap().chars() {
println!("{}", c);
}
println!("next line");
}
}
很难从你的解释中理解你真正想要的,但如果你想从输入中读取没有换行符的每一行,你可以使用 lines()
迭代器。以下是新 std::io
的版本:
use std::io::BufRead;
let input = std::io::stdin();
for line in input.lock().lines() {
// here line is a String without the trailing newline
}