c++stringbinaryatoi

why atoi() function from #include<cstdlib> is not working


I created a program to convert a number into its binary format using a string(r), now I want to convert it into integer data type, I found atoi() function(import from cstdlib) on google for conversion from string to integer but its not working.

Here is my code- it shows error click here to see it

#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
    int num,n;string r;
    cout<<"Enter the number : ";
    cin>>num;
    while(num!=0){r = (num%2==0?"0":"1")+r;num/=2;}
    cout<<"\nBinary value is "<<r<<endl;
    n = atoi(r);
    cout<<n;
    return 0;
}

Solution

  • atoi() expects a const char * (an array of char), where r is a std::string object. You can convert a string to const char * with it's c_str() method.

    atoi(r.c_str())