user1895783
user1895783

Reputation: 381

Converting a const string into an array of ints?

Hello I am trying to convert a const character string into an array of ints but when I try it does not allow it. My code is:

int isRegistered(const char str[]) {

int isbnInt[10], i;
//char isbnArray[10];

//isbnArray = str;  ----> something I tried

for (i = 0; i < 10; i++)
{
    isbnInt[i] = atoi(str[i]);
    cout << isbnInt[i] << endl;
}
}

But when I try to compile it, I get an error saying "invalid conversion from char to const char*"

Upvotes: 0

Views: 331

Answers (3)

Dean J
Dean J

Reputation: 40298

Your code could also be written:

for (i = 0; i < 10; i++)
{
    char foo = str[i];
    isbnInt[i] = atoi(foo);
    cout << isbnInt[i] << endl;
}

Which won't work (as you've found); atoi expects a char*, not a char.

Try:

 int isbm = atoi(str);

and see if that does what you wanted.

Upvotes: 0

billz
billz

Reputation: 45410

Try:

for (i = 0; i < 10; i++)
{
    isbnInt[i] = str[i] - '0';
    cout << isbnInt[i] << endl;
}

atoi takes const char* as input instead of single char.

Upvotes: 0

Karthik T
Karthik T

Reputation: 31952

atoi call expects a const char * arguement, while you pass a char, this is the problem.

You can just do the below to convert the character to number. This subtracts the ascii value of 0 from the character itself ( since 0-9 are sequentially increasing in the ascii code.)

isbnInt[i] = str[i] - '0';

Upvotes: 3

Related Questions