Reputation: 381
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
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
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
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