IT’s Portfolio

[Rust] How to study Rust? - "Copycat" (5) 본문

Development Study/Rust

[Rust] How to study Rust? - "Copycat" (5)

f1r3_r41n 2023. 9. 23. 15:16
728x90
반응형

단어를 모두 연결, 각 단어의 시작 위치를 단어와 함께 출력하고, 마지막에 총 길이 출력(16진수 사용)


입력 파일

sample.s
34 B


소스 코드

use std::{fs, io::Read, error::Error, process};

fn read_file() -> Result<String, Box<dyn Error>> {
    let mut f = fs::File::open("sample.s")?;
    let mut buf = String::new();
    f.read_to_string(&mut buf)?;
    Ok(buf)
}

fn word_position(contents: String) {
    let mut text = String::new();
    let mut p = 0;
    for word in contents.lines() {
        println!("{p:02X}: {word}");
        text.push_str(word);
        p+=word.len();
    }
    println!("{:02X}", text.len());
}

fn main() {
    let contents = read_file().unwrap_or_else(
        |err| {
            eprintln!("Error!\n{err}");
            process::exit(1);
        }
    );
    word_position(contents);
}

결과

00: apple
05: orange
0B: school
11: tomato
17: man
1A

출처

728x90
반응형
Comments