Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore the line break while printing a string read from stdin?

I tried to write a bit of code which reads a name from stdin and prints it. The problem is the line breaks immediately after printing the variable and the characters following the variable are printed in the next line:

use std::io;

fn main() {
    println!("Enter your name:");
    let mut name = String::new();
    io::stdin().read_line(&mut name).expect("Failed To read Input");
    println!("Hello '{}'!", name);
}

The '!' is printed in the next line, which is not the expected location.

enter image description here

like image 770
Sriram Avatar asked Apr 23 '17 03:04

Sriram


People also ask

Does read () Read in New Line?

No, read() system call doesn't add any new line at end of file.

How do you ignore N input in python?

Remove \n From String Using regex Method in Python To remove \n from the string, we can use the re. sub() method.

How do you Linebreak a string?

Create a string containing line breaksInserting a newline code \n , \r\n into a string will result in a line break at that location. On Unix, including Mac, \n (LF) is often used, and on Windows, \r\n (CR + LF) is often used as a newline code.


1 Answers

Use .trim() to remove whitespace on a string. This example should work.

use std::io;

fn main() {
    println!("Enter your name:");
    let mut name = String::new();
    io::stdin().read_line(&mut name).expect("Failed To read Input");
    println!("Hello '{}'!", name.trim());
}

There also trim_start() and .trim_end() if you need to remove whitespace changes from only one side of the string.

like image 97
4e554c4c Avatar answered Sep 22 '22 08:09

4e554c4c