Logo

Programming-Idioms

  • Ruby
  • C++
  • Haskell
  • C#
  • Rust
let i = match s.parse::<i32>() {
  Ok(i) => i,
  Err(_e) => -1,
};

s is parsed to 32-bits signed integer here (change number type if needed).
-1 is used here as a fallback value, but any error handling instructions can be used.
let i: i32 = s.parse().unwrap_or(0);

This explicitly sets the value to 0 if it can't be parsed to an integer.
let i = s.parse::<i32>().unwrap();

This panics if s is not a valid number.
s is parsed to 32-bits signed integer here (change number type if needed).
i = s.to_i

to_i returns 0 if s is not a valid number.
std::string s("123");
int i;
std::from_chars(s.data(), s.data() + s.size(), i, 10);
#include <cstdlib>
int i = std::atoi(s);

s is a char*
#include <string>
int i = std::stoi(s);
#include <string>
#include <sstream>
std::stringstream ss(str);
int i;
ss >> i;
let i = read s :: Integer
long i = Convert.ToInt64(s);

May throw FormatException and OverflowException.
ToInt32 also exists.
int i = int.Parse(s);

Throws an error if s can't be converted. int can be replaced with any number data type.
I : Integer := Integer'Value (s);

New implementation...