Advertisement
SetKaung

Untitled

Dec 8th, 2023
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.25 KB | Source Code | 0 0
  1. use std::io::{self, Write};
  2.  
  3. fn main() {
  4.     let mut input = String::new();
  5.     let mut integer = 0;
  6.     let mut total = 0;
  7.     while integer >= 0 {
  8.         print!("Enter a positive integer (to exit, enter a negative number): ");
  9.         io::stdout().flush().expect("can't flush std out.");
  10.         match io::stdin().read_line(&mut input) {
  11.             Ok(_) => {}
  12.             Err(err) => eprintln!("error reading from standard input. ERR: {}", err),
  13.         }
  14.         match input.strip_suffix("\n") {
  15.             Some(str) => input = str.to_string(),
  16.             None => {
  17.                 println!("You entered nothing.");
  18.                 continue;
  19.             }
  20.         }
  21.         match input.parse::<i32>() {
  22.             Ok(value) => {
  23.                 if value < 0 {
  24.                     break;
  25.                 }
  26.                 integer += 1;
  27.                 total += value;
  28.             }
  29.             Err(err) => eprintln!(
  30.                 "invalid input {input}. must be a postive or negative integer. ERR: {err}"
  31.             ),
  32.         }
  33.         input.clear();
  34.     }
  35.     if integer > 0{
  36.         println!("The total numbers of positive integers entered is {integer}");
  37.     }
  38.     println!("The sum of all positive integer(s) is {total}.");
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement