Compare and contrast C++ and Rust
First, please write a program with very good comments to add two integers in C++, and then write the same program in Rust so that one can compare and contrast the 2 programming languages.
C++:
#include <iostream> // Include the input/output stream library
int main() {
// Declare variables to hold the two integers
int num1, num2;
// Prompt the user to enter the first integer
std::cout << "Enter the first integer: ";
std::cin >> num1;
// Prompt the user to enter the second integer
std::cout << "Enter the second integer: ";
std::cin >> num2;
// Calculate the sum of the two integers
int sum = num1 + num2;
// Display the result
std::cout << "The sum of " << num1 << " and " << num2 << " is " << sum << std::endl;
return 0; // Indicate successful program execution
}
Rust:
use std::io; // Import the standard I/O module
fn main() {
// Declare variables to hold the two integers
let mut num1 = String::new();
let mut num2 = String::new();
// Prompt the user to enter the first integer
println!("Enter the first integer: ");
io::stdin().read_line(&mut num1).expect("Failed to read line");
// Convert the input to an integer
let num1: i32 = num1.trim().parse().expect("Please enter a valid number");
// Prompt the user to enter the second integer
println!("Enter the second integer: ");
io::stdin().read_line(&mut num2).expect("Failed to read line");
// Convert the input to an integer
let num2: i32 = num2.trim().parse().expect("Please enter a valid number");
// Calculate the sum of the two integers
let sum = num1 + num2;
// Display the result
println!("The sum of {} and {} is {}", num1, num2, sum);
}