twerk_it_606
twerk_it_606

Reputation: 63

error: invalid conversion from ‘char’ to ‘const char*

In the following code

#include <stdlib.h> //atoi
#include <string>   

using namespace std;

namespace roman
{
    string convert( int input )
    {
        string inputStr = to_string(input);
        if(inputStr.size()==4)
        {
            return string( atoi( inputStr[0] ), 'M')+convert(stoi(inputStr.substr(1, npos)));//error here
        }
    }
}

I am getting the titular error in the return line. I think it has something to to with the atoi function. It takes a const char* as the input value. I need to know how to turn the first character in inputStr into a const char*. I tried appending .c_str() to the end of inputStr[0], but that gave me the error request for member c_str which is of non-class type char. Anyone have some ideas?

Upvotes: 1

Views: 1505

Answers (2)

Alan Stokes
Alan Stokes

Reputation: 18972

inputStr[0] is a char (the first char of inputStr); atoi wants a pointer to a null-terminated sequence of chars.

You need inputStr.c_str().

EDIT: If you really want just the first character and not the whole string then inputStr.substr(0, 1).c_str() would do the job.

Upvotes: 3

KalyanS
KalyanS

Reputation: 527

You are indexing

inputStr[0]

to get at a single character. This is not a string and atoi() cannot digest it.

Try constructing a string of one character and call atoi() with that.

Something like,

atoi( string(1, inputStr[0]) );

might work. But, that is not the only or best way as it creates a temporary string and throws it away.

But, it will get you going.

Upvotes: 0

Related Questions