0
votes

My goal is to first read an integer n, then n pairs of integers, outputting their sum.

A sample input would be:

3
1 2
2 2
1 3

And its respective output would be:

3
4
4

Here's what I have so far;

use std::io::stdin;

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

    let n: i32;
    stdin().read_line(&mut buff).unwrap();
    n = buff.trim().parse().unwrap();

    let mut sum;
    for _ in 0..n {
        stdin().read_line(&mut buff).unwrap();
        sum = buff
            .trim()
            .split_whitespace()
            .map(|x| x.parse::<i32>().unwrap())
            .sum::<i32>();
        println!("{}", sum);
    }
}

But it looks like the sum variable is carrying forward with each iteration of the loop.

1

1 Answers

2
votes

stdin.read_line(&mut buff) reads from stdin and appends it to buff, it does not clear the old contents. You need to call buff.clear() on every iteration:

for _ in 0..n {
    buff.clear(); // <- this
    stdin().read_line(&mut buff).unwrap();
    sum = buff
        .trim()
        .split_whitespace()
        .map(|x| x.parse::<i32>().unwrap())
        .sum::<i32>();
    println!("{}", sum);
}