Learn C++ | atoi vs stoi
1 min readFeb 19, 2019
atoi
& stoi
are the two ways in which type casting can be done in C & C++ respectively.
Uses:
- Type casting from
string
toint
.
Concepts covered:
- initialize a string with a dummy value.
- Convert the
string
toint
in C, C++. - add
5
to theint
value. - Display the result in both C, C++.
Video:
Part 1:
Part 2:
Code snippet:
#include <iostream> // std::cout
#include <string> // std::string, std::stoiint 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;
}
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