Converting string to int in Turbo C

1.3k Views Asked by At

Good day! Can I ask how to convert a string to int in turbo C. For example:

void comp()
{
    FILE *fp;
    int i,x;
    long int deci;
    char bin[8];
    char *str=0;
    char buf[1024];

    fp=fopen("C:\enc.txt","w");

    printf("Enter a text: ");
    scanf("%[^\n]",str);
    init(str);

    for(i=0;i<128;i++)
    {
        if(code[i])
        {
            printf("'%c': %s\n",i, code[i]);
        }
    }

I'm making a binary code here with the use of string.

    encode(str, buf);
    deci=decimal(buf);
    printf("%li", deci);

    fprintf(fp,"%s",deci);

    fclose(fp);

}

Here is the function decimal()

int decimal(long int decimal)
{
    int dc, power;
    power=1;
    ht=0;
    while(decimal>0)
    {
        dc+=decimal%10*power;
        decimal=decimal/10;
        power=power*2;
    }
    return dc;
}

Thanks for the responses!

2

There are 2 best solutions below

1
On

I'll assume you are reading a stream of integers as string, and want them to be converted into integers.

Create a new integer array. Run a loop and convert each character into an integer.

int *buf = new int[strlen(str)];
for(int i=0; i < strlen(str)-1; ++i)
{
       buf[i] = str[i] - '0';
}

And here you have, all the integer data stored into an integer array.

EDIT:

If you want to store the string into an integer,

long long number = 0;
for(int i = strlen(str) - 2; i >= 0; --i)
{
        number *= 10;
        number += buf[i];
}
0
On

I know, I'm little late, but it will definitely help others.

Use built-in function atoi which is available in stdlib.h

#include <stdlib.h>
    char a[2]="10";
    int b = atoi(a) + 5;