'create_dir() adds weird question mark to the folder, when the folder name uses input [duplicate]

In one section of my program, it creates a folder that is named after the input that the user gives:

        println!("\nName your world\n");

        let mut name = String::new();

        io::stdin().read_line(&mut name).expect("Error Reading Input!");

        let mut name_path = format!("saves/{}",name);

        fs::create_dir(Path::new(&name_path)).unwrap();
        println!("\nWorld Created!\n");

It ran succesfully(I created a Folder called test_world), but when i viewed the folder, i noticed that it was named: test_world? I have run the program multiple times, and with different folder names, but it turns out the same(X?). Example



Solution 1:[1]

That is probably because of the newline character attached at the end of the string. You should call .pop() to remove the trailing newline or better yet the .trim() function that removes all preceding and trailing whitespace characters.

BTW you should use a PathBuf for working with paths Here's the code

use std::{io, fs, path::PathBuf};

fn main() {
    println!("\nName Your World\n");
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).unwrap();
    let trimmed_path = buffer.trim();

    let mut path = PathBuf::from("saves");
    path.push(trimmed_path);

    fs::create_dir(&path).unwrap();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arijit Dey