-3

im trying to create a calculator with a that if the user writes that he doesnt want to do another operation it breaks it never does.

fn main {
    loop {
// calculator code
println!("result: {}", result);
        println!("do you want to do another operation(y/n)? ");
        let mut answer = String::new();
        io::stdin().read_line(&mut answer).expect("failed to read line");
        if answer == "n"{
            println!("ok, goodbye!");
            break;
        } 
    }
}

this is my first rust project so i tried very little

alvinn011
  • 1
  • 1

1 Answers1

2

The read_line() function reads until \n is found, but this delimiter is included in the updated string.

At least, you have to analyse the answer like this:

if answer == "n\n" {

See this documentation (referring to this one).

This function will read bytes from the underlying stream until the newline delimiter (the 0xA byte) or EOF is found. Once found, all bytes up to, and including, the delimiter (if found) will be appended to buf.

Alternatively, you can rely on the .trim() function. It returns a string-slice (partial view on the original string) ignoring the leading and trailing whitespaces.

if answer.trim() == "n" {
prog-fh
  • 13,492
  • 1
  • 15
  • 30