1

I am taking a user input and then concatenating that user input with a String. But output is showing in two different lines. Any method to be placed so that "\n" gets removed and the both prints on the same line. I have tried .trim() but it's not working.

fn main () {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).expect("_");
    s.trim();
    s.push_str(",World");
    println!("{}",s);
}

Output I am getting.

hello      
hello
,World

Output I want.

hello      
hello,World

Solved:

fn main () {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).expect("_");
    s.pop();
    s.push_str(",World");
    println!("{}",s);
}
  • 3
    How have you tried `.trim()`? Could you [edit] your question and tell us? Also: did you notice the "warning: unused return value of `core::str::::trim` that must be used"? – Lukas Kalbertodt Sep 02 '19 at 09:06
  • I have edited the question and no i didn't get this warning. – Muhammad Areeb Siddiqui Sep 02 '19 at 09:09
  • 2
    Thanks for editing! Are you sure about the warning? I copied your code [into Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=eb5f249babe05520e6746b4a95155219) and compiling it there produces the warning. Which Rust version are you using (`rustc -V`)? Have you disabled warnings somehow? – Lukas Kalbertodt Sep 02 '19 at 09:11
  • Yes you are right I also get this warning on Rust Playground. But there is no warning on my rust version 1.35.0 and i havenot disabled any warnings. – Muhammad Areeb Siddiqui Sep 02 '19 at 09:14
  • 1
    Very interesting. I just installed 1.35 locally and get that warning with that compiler version. So something's fishy in your setup (maybe check the `RUST_FLAGS` env variable?). In any case, as you probably learned from the warning, `trim` does not modify the original string. You probably want to use `pop()` or `truncate()`. See [this](https://stackoverflow.com/q/37888042/2408867) Q&A for more information. Would you be fine with closing your question as a dupe of the linked one? – Lukas Kalbertodt Sep 02 '19 at 09:25
  • Thanks Lukas Kalbertodt ! I solved this by "s.pop()". – Muhammad Areeb Siddiqui Sep 02 '19 at 09:33
  • 1
    Glad we could help! – Lukas Kalbertodt Sep 02 '19 at 09:33

0 Answers0