typedefcoder2
typedefcoder2

Reputation: 300

atoi conversion to return a single digit value

I have a character array like this :

+---+---+---+
|53.|.7.|...|
|6..|195|...|
|.98|...|.6.|
+---+---+---+

I am using an int array to store particular values at specific indexes. For conversion i have used

            for(int i=0;i<27;i++)
        {
        inputNumArray[i]=atoi(&inputInitial[indexArray[i]]);        
        }

now the problem is my desired out put is :

5       3      0       0       7       0       0       0       0
6       0      0       1       9       5       0       0       0
0       9      8       0       0       0       0       6       0

and the code returns me this :

53      3       0       0       7       0       0       0       0
6       0       0       195     95      5       0       0       0
0       98      8       0       0       0       0       6       0

I assume the reason is that atoi scans till it finds character and for atoi(&inputInitial[i]) it will read till i+1, i+2... and so on till it encounters an error. I want to restrict the atoi scanning to a single character only. Is it possible or shall i use some other function ?

Upvotes: 3

Views: 1646

Answers (5)

sehe
sehe

Reputation: 393477

The input format is not clear to me. However, here's what I'd do for an array:

char x[] = "12345678";
int out[] = new out[strlen(x)];

int* oit = out;
for (char* it=x; it < x+sizeof(x);)
     *oit++ = (*it++)-'0'


// out[] now contains char-by-char value as int

Upvotes: 0

Marshall Clow
Marshall Clow

Reputation: 16680

atoi expects a null terminated sequence of characters.

Better to write your own function that takes a single char, like:

int ctoi ( char ch ) {
    if ( ch >= '0' && ch <= '9' ) return ch - '0';
    return -1; // error
    }

Upvotes: 0

zmbq
zmbq

Reputation: 39023

Don't use atoi, just use this:

if(isdigit(c))
    val = c - '0';
else
    val = 0

Upvotes: 10

a-z
a-z

Reputation: 1664

you can temporarily change the value of next character to 0 in your string so a to i just reads one digit.

Upvotes: 0

K-ballo
K-ballo

Reputation: 81379

You arrumption about atoi is correct. If you want a single digit to be converted, you can create a string that contains just that:

char temp[2] = { inputInitial[indexArray[i]], '\0' );
inputNumArray[i] = atoi( temp );

Upvotes: 1

Related Questions