1

I'm trying to convert a character from a string into an int. I tried this :

int function(char c[]) {
     return (int)c[1];
}

I want to convert only the second character of the string c, which length is only of two.

The problem with this function is that the integer returned is completely different from what I typed.

I also tried to compare c[1] and numbers from 0 to 10 (only those numbers need to be converted), but there's a problem with c[1].

I hope everything is clear enough so you can help me.

Thanks !!!

Answer : I just changed return(int)c[1]; into return(int)(c[1]-'0'); and that worked well, at least for me

LoneRetriever
  • 119
  • 10
  • Please post the [Minimal Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) with complete code (perhaps a dozen more lines) that demonstrates the problem, and show *what* you typed. – Weather Vane Apr 10 '20 at 19:40
  • 2
    Does this answer your question? [How to convert a single char into an int](https://stackoverflow.com/questions/439573/how-to-convert-a-single-char-into-an-int) – Ruud Helderman Apr 10 '20 at 19:41
  • 2
    If `c` contains a digit `'0'`..`'9'`, then to get an integer value `0`..`9`, you need `c - '0'`. The value of `'0'` is usually 48 — in code sets based on ISO 8859 (and ASCII). Only in EBCDIC (used by some mainframes) is the value different; there, `'0'` is usually 240. – Jonathan Leffler Apr 10 '20 at 19:48
  • Thanks Jonathan Leffler, that worked perfectly fine for me – LoneRetriever Apr 11 '20 at 10:48

3 Answers3

0

I think you want to convert the char into its ASCII (integer) form.

printf("The ASCII value of %c = %d\n",i,i);

If you want to convert an integer into char, simply use explicit casting like below:

char c1 = (char)97;  //c1 = 'a'
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Nesan Mano
  • 1,892
  • 2
  • 26
  • 43
0

Try this out:

#include<stdio.h>

int function(char c[]);

int main(void) {
    char characters[3] = {'a','b','c'};

    int a = function(characters);

    printf ("%d",a);

    return 0;
}

int function(char c[]) {
     return (int)c[1];
}
xafak
  • 21
  • 1
  • 1
  • 7
-1

try this:-

int function(char c[]) {
    int x=0;
    try {
        x = Integer.parseInt(String.valueOf(c[1]));
    }catch (NumberFormatException e){
        x=c[1];
    }
    return x;
}
Rahul Samaddar
  • 244
  • 2
  • 8
  • 1
    Using a C++ construct (`try { … } catch …`) in C code (the question is tagged [tag:c] and not [tag:c++]) isn't helpful. Your code converts the second character in `c` to a string, parses the string to see if it is an integer, and captures an exception to spot when the character is bogus. That's a very heavy-duty way of testing whether each character is a digit. I'm not convinced by the error recovery in the `catch` clause. Please delete this (before it's down-voted). – Jonathan Leffler Apr 10 '20 at 20:14