0

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

Macho Onion
  • 207
  • 2
  • 8
  • 2
    `read_line` will include the newline character. Does this answer your question [Why does my string not match when reading user input from stdin?](https://stackoverflow.com/q/27773313/2189130) – kmdreko Jan 31 '22 at 19:41

2 Answers2

2

read_line() includes the trailing newline, if present. For example, try running this code:

fn main() {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).unwrap();
    println!("Hello, world! '{}'", s);
}

to fix this, you can use .trim() to remove whitespace from the beginning and end of your input: https://doc.rust-lang.org/std/primitive.str.html#method.trim

lkolbly
  • 1,140
  • 2
  • 6
0

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();
}
Arijit Dey
  • 316
  • 2
  • 10