Thread: char array string > integer

  1. #1
    budding software engineer luigi40's Avatar
    Join Date
    Jun 2004
    Location
    South Coast UK
    Posts
    61

    Question char array string > integer

    im sure this has been answered before on here, however after searching using the keyword 'convert' and going through half an hours worth of replies my question wasnt answered.

    im trying to convert a char array ( of numbers like
    [7][2][6][4][5][6]) to one whole integer like 726456 (decimal)
    (which have been converted from ascii to dec)

    so i can perform maths calculations on the integers then output result to screen.

    is there an easier way other than looping through each element, adding the column, if greater than 10, carry etc

    atoi will not work as i just get zero because it expects ascii as input, is there a version of atoi for my question?

    luigi

  2. #2
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Basic method.

    int total = 0;
    A:
    Multiple total by 10 and store in total
    Add the number ( think char - '0' )
    Go back to A and repeat until there are no more characters

    total is now the value

    So using your example

    Code:
    int total=0;
    
    total *= 10;
    total += 7;
    total *= 10;
    total += 2;
    total *= 10;
    total += 6;
    total *= 10;
    total += 4;
    total *= 10;
    total += 5;
    total *= 10;
    total += 6;
    
    printf("%d\n", total);

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Why don't you just use atoi?

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  2. initialization of char array (c style string)
    By manzoor in forum C++ Programming
    Replies: 1
    Last Post: 09-24-2008, 06:29 AM
  3. OOP Question DB Access Wrapper Classes
    By digioz in forum C# Programming
    Replies: 2
    Last Post: 09-07-2008, 04:30 PM
  4. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  5. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM