Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io::{self, Write};
- fn main() {
- let mut input = String::new();
- let mut integer = 0;
- let mut total = 0;
- while integer >= 0 {
- print!("Enter a positive integer (to exit, enter a negative number): ");
- io::stdout().flush().expect("can't flush std out.");
- match io::stdin().read_line(&mut input) {
- Ok(_) => {}
- Err(err) => eprintln!("error reading from standard input. ERR: {}", err),
- }
- match input.strip_suffix("\n") {
- Some(str) => input = str.to_string(),
- None => {
- println!("You entered nothing.");
- continue;
- }
- }
- match input.parse::<i32>() {
- Ok(value) => {
- if value < 0 {
- break;
- }
- integer += 1;
- total += value;
- }
- Err(err) => eprintln!(
- "invalid input {input}. must be a postive or negative integer. ERR: {err}"
- ),
- }
- input.clear();
- }
- if integer > 0{
- println!("The total numbers of positive integers entered is {integer}");
- }
- println!("The sum of all positive integer(s) is {total}.");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement