Thread: string to int conversion not using atoi()

  1. #1
    Advanced Novice linucksrox's Avatar
    Join Date
    Apr 2004
    Location
    Michigan
    Posts
    198

    string to int conversion not using atoi()

    I'm trying to figure out how to convert a string to an int without using atoi(). I'm doing a programming excersise from a book I'm reading, and it says
    "Use the character classification functions to prepare an implementation of atoi()." So that means using the ctype.h functions...
    But short of creating an entire algorithm to find the number of digits of the int, then multiplying the 1st digit by 10^n, then add the second digit times 10^n-1 and so on. Is that what I need to do? Or is there a way simpler process to do this? Maybe someone could just explain how the atoi() function does its thing, I couldn't find the source code anywhere through google and just opening up stdlib.h didn't make much sense to me...

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Basically it works like this:
    Code:
    string: 150
    sum: 0
    pointer to the character 1
    begin loop
      sum = sum * 10
      sum = sum + the number pointer is pointing to
      move pointer to next character
      if we aren't pointing to the end of the string, repeat the loop
    end loop
    
    sum now holds the value
    broken down by example (loop unrolled)
    Code:
    string = 125
    sum = 0
    
    sum = sum * 10 // 0 * 10 is still 0
    sum = sum + 1  // Now sum is 1
    
    sum = sum * 10 // Now sum is 10
    sum = sum + 2  // Now sum is 12
    
    sum = sum * 10 // Now sum is 120
    sum = sum + 5  //  Now sum is 125

  3. #3
    Advanced Novice linucksrox's Avatar
    Join Date
    Apr 2004
    Location
    Michigan
    Posts
    198
    Thanks Thantos, I understand it and that's definitely a much better way than what I was about to do. That way I don't have to check the number of digits and use that as an exponent to 10 to multiply each digit, if you catch my drift. Now all I gotta do is make the function read in the string and create another string that is only an int, and go from there.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. NEED HELP READING FILE and PRINTING
    By geoffr0 in forum C Programming
    Replies: 4
    Last Post: 04-16-2009, 05:26 PM
  2. how to combine these working parts??
    By transgalactic2 in forum C Programming
    Replies: 0
    Last Post: 02-01-2009, 08:19 AM
  3. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM
  5. How do you search & sort an array?
    By sketchit in forum C Programming
    Replies: 30
    Last Post: 11-03-2001, 05:26 PM