Home > Software engineering >  How do I convert Char to Int, with the value remaining the same?
How do I convert Char to Int, with the value remaining the same?

Time:10-30

I have to get a string from keyboard, and then print only the numbers from the char, but with the actual value.

**Example ** Input: I am 19 years old output: 19 (as an integer)

I wrote this code, but I cant convert it whatever I do.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void main()
{
    char sir[20];
    int i=0;
    printf("Introduceti varsta sub forma - Eu am X ani. - : ");
    gets(sir);
    while(sir[i]!='\0')
    {
        if(sir[i]>='0' && sir[i]<='9')
        {
            int nr = atoi(sir[i]);
            printf("%d", nr);
        }
        i  ;
    }

CodePudding user response:

The function atoi expects a pointer of the type char * while you are passing an object of the type char.

Instead of this record

int nr = atoi(sir[i]);

just write

int nr = sir[i] - '0';

Pay attention to that the function gets is unsafe and is not supported by the C Standard. Instead use fgets.

  • Related