Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Comparing two strings in Rust

I am trying to compare two strings in Rust for a project I am doing in my free time in order to become more familiar with Rust, however I have run in to a small issue. Whenever I try to do string1 == string2 all I get is false. Here is the code that I am using:

use std::io;

fn main() {
    let mut username = String::new();
    let mut password = String::new();

    let username = "Miku";
    let password = "password";

    loop{
        let mut userAttempt = String::new();
        let mut passAttempt = String::new();

        println!("Enter username:\n> ");
        io::stdin().read_line(&mut userAttempt).expect("Failed to read line");

        println!("Enter password:\n> ");
        io::stdin().read_line(&mut passAttempt).expect("Failed to read line");

        println!("{}", userAttempt == username);

        if userAttempt == username{
            println!("Got here!");

            if passAttempt == password{
                println!("Logged in successfully.");
            }
        }
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Check https://doc.rust-lang.org/stable/std/io/trait.BufRead.html#method.read_line – the return value from read_line contains the new line character.

You could do if userAttempt.trim() == username{ ... to remove the additional space characters

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading