How can we convert a string to int without a standard lib

the string termination can be '/r'

Recommended Answers

All 4 Replies

In a loop, convert each byte to binary then add to an int accumulator, for example assume you have a character array named "msg" and a loop counter named "i"
sum = (sum * 10) + msg[i] - '0';

Here's some working code:

#include <stdio.h>

int main(int argc, char** argv)
{
    int i=0,j=0;
    int p = 1;
    int size = 0;
    char input[100];

    scanf("%s",input);

    while(input[size] != '\0') ++size;

    while(i<size) {
        char c = input[size-1-i];
        if( c < '0' || c > '9')
            return 1;
        j += (c - '0')*p;
        p *= 10;
        ++i;
    }

    printf("%d\n",j);

    return 0;
}

You can also read some comments here:
http://www.bytelead.be/reviewlead/review.php?team=Pieter&review_id=8

Pieter
Bytelead

commented: We don't do homework for people - he *help* them find their own solutions +14
int main (void)
 {
  char ch;
  int num = 0;

  //get char
 while((ch = getchar()) != '\n')
    {
        //if its between 0 and 9
      if((ch >= '0' && ch <= '9'))
        {
           num = (int)ch - '0';        //convert in to int
           }
      }
      }
commented: code remembers only single digit not whole integer! +0

hi hwoarang69
you did right it wil will work.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.