error: invalid conversion from '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' {aka 'char'} to 'const char*' [-fpermissive]

Viewed 5017

facing error,I'm trying to convert char values is stack to int and then square them.I tried using atoi() and sscanf() but still I'm facing this error

#include <stack>
#include<iostream>
#include<cmath>
#include<string>
#include <sstream> 

using namespace std;
int main(){
        int n;
        std::cin>>n;
        long long int num = n;
        while(num != 1){
            stack<char>s;
            string strnum = to_string(num);
            for(int i=0;i<strnum.size();i++){
                s.push(strnum[i]);
            }
            num = 0;
            while(!s.empty()){
                int x=0;
                //sscanf(s.top(),"%d",&x);
                x = atoi(s.top());
                num += (x*x);
                std::cout << x << std::endl;
                s.pop();
            }
    cout<<"num is : "<<num<<endl;
        }

        std::cout<<1;

}

1 Answers

In this call

x = atoi(s.top());

an object of the type char is passed as an argument to the function atoi that expects an argument of the type char *. Pay attention to that ths stack is defined as a stack of separate characters.

stack<char>s;

You could write

x = s.top() - '0';

If you want to get a number stored in the source string pushed on the stack then write

        const int Base = 10;
        int multiplier = 1;
        num = 0;
        while(!s.empty()){
            int x=0;
            //sscanf(s.top(),"%d",&x);
            x = s.top() - '0';
            num += multiplier * x;
            multiplier *= Base;
            //...

If you want to get the number in the reverse order then write

        const int Base = 10;
        num = 0;
        while(!s.empty()){
            int x=0;
            //sscanf(s.top(),"%d",&x);
            x = s.top() - '0';
            num = Base * num + x;
            //...

Bear in mind that there is standard function std::stoi that does the required conversion of a string to a number.

And you should use an object of the type unsigned int. Otherwise the user can enter a negative number and it will be processed incorrectly. Here is a demonstrative program

#include <iostream>
#include <string>
#include <stack>

int main() 
{
    unsigned int n;
    
    while ( std::cin >> n && n != 0 )
    {
        std::string strnum = std::to_string( n );
        std::stack<char> s;
        
        for ( char c : strnum ) s.push( c );
        
        unsigned long long int num = 0;
        
        while ( !s.empty() )
        {
            unsigned int digit = s.top() - '0';
            num += digit * digit;
            s.pop();
        }
        
        std::cout << "num = " << num << '\n';
    }

    return 0;
}

If to enter the number 123 then its output might look like

num = 14

that is 1 * 1 + 2 * 2 + 3 * 3 == 14.

Related