cpp char to int code example

Example 1: char to int c++

int x = (int)character - 48;

Example 2: string to int c++

// stoi example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

int main ()
{
  std::string str_dec = "2001, A Space Odyssey";
  std::string str_hex = "40c3";
  std::string str_bin = "-10010110001";
  std::string str_auto = "0x7f";

  std::string::size_type sz;   // alias of size_t

  int i_dec = std::stoi (str_dec,&sz);
  int i_hex = std::stoi (str_hex,nullptr,16);
  int i_bin = std::stoi (str_bin,nullptr,2);
  int i_auto = std::stoi (str_auto,nullptr,0);

  std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
  std::cout << str_hex << ": " << i_hex << '\n';
  std::cout << str_bin << ": " << i_bin << '\n';
  std::cout << str_auto << ": " << i_auto << '\n';

  return 0;
}

Example 3: char* to int in cpp

int x = std::stoi("42")

Example 4: converting char to integer c++

int x  = '9' - 48;
// x now equals 9 as an integer

Example 5: char to string c++

std::cout << std::string(1, c) << std::endl;

Example 6: converting char to int in c++

#include <sstream>

using namespace std;

int main()
{
    stringstream str;
    
    str << "1";

    double x;
    str >> x;
}

Tags:

Cpp Example