I want to convert a string to int in C++, the below code is printing the last digit of the sum of the two numbers. I know I can do it with other different ways but I am curious why the below code is showing an error.
Code:
int num1 = 10;
int num2 = 20;
int sum = num1 + num2;
string ans = to_string(sum);
cout<< atoi(ans[ans.length()-1])<<endl;
Error:
prog.cpp: In function 'int main()':
prog.cpp:12:40: error: invalid conversion from '__gnu_cxx::__alloc_traits<std::allocator<char> >::value_type {aka char}' to 'const char*' [-fpermissive]
cout<< atoi(ans[ans.length()-1])<<endl;
^
In file included from /usr/include/c++/5/cstdlib:72:0,
from /usr/include/x86_64-linux-gnu/c++/5/bits/stdc++.h:47,
from prog.cpp:2:
/usr/include/stdlib.h:147:12: note: initializing argument 1 of 'int atoi(const char*)'
extern int atoi (const char *__nptr)
I have used both STOI and ATOI but I am still showing this error.
Can you please tell me why this error is originating and how to solve it.