I have a problem in converting char to integer. My code is as follow:

char lang [2][4] ={"en","fr"};

char ch = lang[0][0];
int i = sprintf("%d",ch); //want to get integer value of 'e' in string "en"

ch = lang[0][1];
int j = sprintf("%d",ch);

The error is "sprintf cannot accept parameter 2 from const char*to char".

pls help me.
Thanks.

Rgds,
su

## All 2 Replies

I think it's:

``int x = atoi(char);``

Probably better ways, but that's how I do it.

Getting the numeric value of a single character is simple:

``````char lang[2][4] = {"en","fr"};
int i = lang[0][0];``````

You're confused with the distinction between value and representation. The values of lang[0][0] and i are identical. The only difference is how they're printed, much like octal, decimal, and hexadecimal. The values are the same, but the representation is different. That's why you can do this:

``````printf ( "%c\n", i ); /* Print i as a character */
printf ( "%d\n", i ); /* Print i as an integer */``````

>int i = sprintf("%d",ch);
This is not how sprintf works. Until you have a stronger foundation in the idioms of C, you should refrain from guessing and use a good reference.

>int x = atoi(char);
That's broken, and you should know better. atoi takes a null terminated string. If you pass it a single character that doesn't have the value of 0, you invoke undefined behavior. Not to mention that atoi will fail and return 0 if the character is non-numeric, which in my world, 'e' most certainly is.

Here's a nice little guideline for both of you: If you don't know, go find out. In C and C++ there's no margin for error, so a guess is just asking for trouble.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.