Learn C++ | atoi vs stoi

Abhijit Roy
1 min readFeb 19, 2019
learn_cpp_atoi_vs_stoi

atoi & stoi are the two ways in which type casting can be done in C & C++ respectively.

Uses:

  • Type casting from string to int .

Concepts covered:

  • initialize a string with a dummy value.
  • Convert the string to int in C, C++.
  • add 5 to the int value.
  • Display the result in both C, C++.

Video:

Part 1:

part 1

Part 2:

part 2

Code snippet:

#include <iostream>  // std::cout
#include <string> // std::string, std::stoi
int main() {
std::string my_str_var = "12356";
int my_int_var_c, my_int_var_cpp;
// C++
my_int_var_cpp = std::stoi(my_str_var);
std::cout << my_int_var_cpp + 5 << '\n';
// C
const char* my_char_var = my_str_var.c_str();
my_int_var_c = atoi(my_char_var);
std::cout << my_int_var_c + 5 << '\n';

return 0;
}

Github code

Thanks!

See you in my next blog post.

Happy Coding :)

Follow my Academy on:

Udemy — https://www.udemy.com/user/blockhub/
Medium — https://medium.com/@abhi3700
Twitter — https://twitter.com/blockhubindia
Github — https://github.com/blockhubindia
Facebook — https://www.facebook.com/blockhubindia/
YouTube — https://www.youtube.com/channel/UCmALtcbNcPUFyWbpF3XyM7Q
Telegram — https://t.me/blockhubindia

--

--

Abhijit Roy

Blockchain (Rust, Solidity, C++, JS/TS) || Data Science (Python) || Bot (Python) || Backend (JS, TS)