Error while computing ascii to decimal

This is a discussion on Error while computing ascii to decimal within the C Programming forums, part of the General Programming Boards category; Hi all, I have written a program that converts a string of ascii numbers into a decimal number. For example, ...

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    69

    Error while computing ascii to decimal

    Hi all,


    I have written a program that converts a string of ascii numbers into a decimal number. For example, if I enter 49 57 56 52 (ascii representations for 1 9 8 4) then it should give me 1984. My program gives me 4555 instead. Below is my code, please suggest changes. Thank you.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    int main()
    {
    char nelements[100];        
    /*nelements is the input string to be converted to decimal consisting of nelements*/
    int n,i,dec=0;
    /*n is the number of elements in the string, i is the index value, dec is used to 
    build converted decimal integer, base0 is the ascii or ordinal value of character 0*/  
    printf("enter the number of elements");
    scanf("%d",&n);
    printf("enter the ascii value of elements");
    for(i=1;i<=n;i++)
    {
        scanf("%s",&nelements[i]);
    }
    for(i=1;i<=n;i++)
    {   
        nelements[i]-=48; 
        dec=dec*10+nelements[i];
    }
        printf("%d",dec);
        system("pause");
        return 0;
    }

  2. #2
    Registered User ~Kyo~'s Avatar
    Join Date
    Jun 2004
    Posts
    320
    atoi() doesn't work for you?

    Edit heres a link even:

    std::atoi, std::atol, std::atoll - cppreference.com

  3. #3
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    You've got the right sort of idea -- your big problem is in how you're storing the input ascii values. You've chosen to put them in a char array and read them with %s. I'm pretty sure this is not what you want! Strings in C are just sequences of characters terminated with a NULL terminator -- so for example for your first input value "49" would be stored in nelements[1], [2] and [3] as '4','9',0. This will be problematic as your 'for' loop increments i by one and so overwrites part of the previous input each time through the loop.

    If you really wanted to store strings, an array of char pointers would be appropriate. However I don't think you do, based on the rest of your code.

    Code:
       nelements[i]-=48;
    Here you're trying to get the numerical value from the ascii encoding, but nelements[i] is just the first character of the first number, which is '4'. You could use the functions Kyo mentioned, if you actually had the whole string, but at this point you don't.

    It would seem to be much simpler to read the ascii input as numbers, not strings. I mean:

    Code:
    int nelements[100]; // change to int to match the data size you'll store in here later
    ..
    ..
    ..
    ..
     scanf("%d",&nelements[i]); //read ints
    I hope that makes sense.


    Couple of other comments on things that aren't causing you immediate problems:
    - system("pause"); isn't portable across platforms - it only works on Windows. It's a bad thing to make a habit of. Suggest you have a look at this FAQ: FAQ > How do I get my program to wait for a keypress? - Cprogramming.com

    - Array indices start from 0, not 1. Your nelements array has 100 elements indexed by 0 to 99. Your current code could attempt to access nelements[100], which doesn't exist. Reading/writing this might crash your program, or might read back garbage, or might 'just work'. Memory corruption creates horrible difficult-to-track bugs and errors - so if you do one thing today fix your array indices and loop terminators

  4. #4
    Registered User
    Join Date
    Jan 2012
    Posts
    69
    Hi Guys,

    Thank you for your replies. My ultimate goal is to write a program to convert the base from decimal to any base between 2 to 36. Here, the input is a decimal value and base in which the number is to be converted and the output is the converted number. The input value may contain characters.

    I have written a program to achieve this, but on running this on dev-c++ forums, my program hangs after inputting the number and the base values. I don't see any error in my code, kindly suggest changes:

    Code:
    
    
    #include<stdio.h>
    #include<stdlib.h>
    int main()
    {
        int newbase,n,i,ascii,ndigit=0,q,r,zero=48;
        char newrep[100];
        printf("Enter the number to be converted");
        scanf("%d",&n);
        printf("Enter the base between 2 and 36 to which the number is to be converted");
        scanf("%d",&newbase);
        zero=atoi(0);
        q=n;
        ndigit=0;
        while(q!=0)
        {
        r=q%newbase;
        ndigit+=1;
        ascii=zero+r;
        if(ascii>atoi(9))
        {
                ascii=ascii+7;
        }
        newrep[ndigit]=(char)ascii;
        q=q/newbase;
        }
        printf("Base %d representation of %d is",newbase,n);
        for(i=ndigit;i<=1;i--)
        {
        scanf("%d",newrep[ndigit]);
        }
        printf("%d",newrep[ndigit]);
        system("pause");
        return 0;       
    }

  5. #5
    Registered User ~Kyo~'s Avatar
    Join Date
    Jun 2004
    Posts
    320
    Um yea.... 0 is not the number 0, but 0 as in the value 0. You could always do int zero = '0'; and use casting though. atoi does something like this:

    Code:
    int number;
    char string_of_numbers[5] = "12345";
    number = atoi(string_of_numbers);
    //number is now equal to 12345
    if you want binary and hex and whatnot there is a function for that already as well...

    use itoa with your value and you can get hex or whatever base you want. An example of itoa:

    Code:
        char temp[15];
        STRING = new char[100];
        strcpy(STRING,"ROTATION: ");
        strcat(STRING,
                 itoa(player->Get_R(),temp,10) // the middle is also the return.  The last parameter is the base of the number.
                );
        textout_ex(BUFFER,font,STRING,32,32,0,-1);

  6. #6
    Registered User
    Join Date
    Mar 2010
    Posts
    535
    Just to expand a bit on that:


    Code:
        zero=atoi(0);
    atoi looks like this:
    Code:
    int atoi ( const char * str );
    You're supposed to pass a string, but you're passing the integer 0 (NULL pointer). I'm not sure what atoi is meant to do with a NULL pointer, but it sure isn't going to interpret it as a string containing "0". You could do

    Code:
    zero = atoi("0");
    But that'd be pointless -- you don't need to use atoi to convert a constant single character - you can just assign it straight to an int by enclosing it in single quotes.

    Code:
    zero = '0';
    And similar anywhere else you want to deal with an ASCII encoding rather than a straight numerical value.

    The last bit of your code from line 28 onwards looks like it's still a work in progress, so I'll not comment on that yet.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 11-07-2011, 10:11 PM
  2. decimal ascII character
    By byfreak in forum C++ Programming
    Replies: 3
    Last Post: 05-24-2008, 10:36 PM
  3. decimal ascII character
    By byfreak in forum C Programming
    Replies: 2
    Last Post: 05-24-2008, 06:37 PM
  4. how to convert decimal number to ASCII code?
    By oie in forum C Programming
    Replies: 11
    Last Post: 11-03-2006, 05:19 PM
  5. HEEEELP: Letters to ASCII decimal equivalents?
    By Mazerius in forum C++ Programming
    Replies: 7
    Last Post: 10-30-2002, 08:56 AM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21