Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I convert Char to Int, with the value remaining the same?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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++;
    }

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading