0

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!

1

2 Answers 2

2

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes. You are right. I should have given the limitation from index 0 to index strlen(str)-2. I'll edit it. :)
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.