#scanf #stdin #input #format

scanf

Parse text inputs (inverse of print! and format!)

10 stable releases

Uses new Rust 2024

1.3.1 Apr 1, 2025
1.3.0 Mar 3, 2025
1.2.3 Jan 7, 2025
1.2.1 Dec 12, 2021
0.0.0 Nov 27, 2021

#477 in Parser implementations

Download history 132/week @ 2024-12-22 47/week @ 2024-12-29 383/week @ 2025-01-05 228/week @ 2025-01-12 183/week @ 2025-01-19 66/week @ 2025-01-26 139/week @ 2025-02-02 181/week @ 2025-02-09 112/week @ 2025-02-16 162/week @ 2025-02-23 253/week @ 2025-03-02 203/week @ 2025-03-09 235/week @ 2025-03-16 157/week @ 2025-03-23 195/week @ 2025-03-30 127/week @ 2025-04-06

745 downloads per month
Used in 3 crates

Unlicense

18KB
399 lines

Scanf

If you know it from C, same functionality but with memory safety.

scanf! & sscanf!

use scanf::scanf;

let mut number: u32 = 0;
let mut name: String = String::new();
if scanf!("{},{}", number, name).is_ok() {
    println!("Input is: {} and {}", number, name);
}
use scanf::sscanf;

let input = "5,something";
let mut number: u32 = 0;
let mut name: String = String::new();
if let Err(error) = sscanf!(input, "{},{}", number, name) {
    panic!("Error {} using sscanf!", error);
}

Examples

use scanf::scanf;

let mut product: String = String::new();
let mut price: f32 = 0.0;
println!("Insert product and price (product: price):");
if scanf!("{}: {}", product, price).is_ok() {
    println!("Price of {} is {:.2}", product, price);
}
use scanf::sscanf;

let input: &str = "Candy: 2.75";
let mut product: String = String::new();
let mut price: f32 = 0.0;
println!("Insert product and price (product: price):");
sscanf!(input, "{}: {}", product, price);
println!("Price of {} is {:.2}", product, price);
# assert_eq!(product, "Candy");
# assert_eq!(price, 2.75);

It's possible to indicate the type in the format string:

# use scanf::scanf;
let mut product: String = String::new();
let mut price: f32 = 0.0;
println!("Insert product and price (product: price):");
scanf!("{string}: {f32}", product, price);
# println!("Price of {} is {:.2}", product, price);

Also escape brackets:

# use scanf::sscanf;
let input: &str = "{Candy}";
let mut product: String = String::new();
sscanf!(input, "{{{}}}", product);
assert_eq!(product, "Candy");

Examples has been compiled and sscanf's examples also ran as tests. If you have problems using the example code, please, create an issue.

Dependencies

~1MB
~17K SLoC