0

I'm solving a programming puzzle in Rust, but there seems to be something wrong with how I'm handling input.

My program returns a different answer for (seemingly) the same input on two different lines, which shouldn't be happening since my algorithm is deterministic.

2
a
a

Here's the code:

use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("");
    let num = input.trim().parse::<i32>().unwrap();

    for _ in 0..num {
        let mut word = String::new();
        io::stdin().read_line(&mut word).unwrap();

        for c in 0..word.len() {
            let mut wordtemp = word.clone();
            wordtemp.insert(c, 'a');
            if wordtemp != wordtemp.chars().rev().collect::<String>() {
                println!("YES");
                print!("{}", wordtemp);
                break;
            } else if c == word.len()-1 {
                println!("NO");
            }
        }
    }
}
mark
  • 85
  • 4
  • 16

1 Answers1

1

I figured out the problem: read_line, includes whitespace, which was causing an issue. You can call .trim() to remove it.

let mut word = String::new();
        io::stdin().read_line(&mut word).unwrap();
        word = word.trim().to_string();
mark
  • 85
  • 4
  • 16