Thread: quick n easy question

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    10

    quick n easy question

    why is the bold part of that line included? i understand 0 in ascii is nul, but don't know why it needs to be removed from the integer value that has been loaded into variable c

    Code:
    getnum(){
       int c, value;;
    
       value = 0;
       c = getchar();
       while(c != '\n'){
          value = 10*value + c - '0';
          c = getchar();
       }
       return (value);
    }

  2. #2
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    i understand 0 in ascii is nul
    Be careful about this. '0' is not nul. '0' is 48 decimal in ASCII. '\0' is 0 (nul). But the program isn't using 0 (0), it's using '0' (48).

    '0' is useful when you have the character representation of an integer. Let's say you get input from a user and they type '5'. Well, if you want to use that as the integer 5 you have to do some math because '5' (in ASCII) is actually 53 decimal. So if you do '5' - '0' (which is 53 - 48) you get the integer value 5. By subtracting '0' from the ASCII character representation of a number you get that number's integer value.
    Last edited by itsme86; 11-10-2005 at 01:28 PM.
    If you understand what you're doing, you're not learning anything.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    10
    perfect explanation. that helps in some other problems i was having...thank you ver much.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Easy String position question...
    By Striph in forum C Programming
    Replies: 4
    Last Post: 05-11-2009, 08:48 PM
  2. Quick Easy Question
    By St0rmTroop3er in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 02-24-2004, 01:08 AM
  3. Quick Question on File Names and Directories
    By Kyoto Oshiro in forum C++ Programming
    Replies: 4
    Last Post: 03-29-2002, 02:54 AM
  4. * quick question *
    By SavesTheDay in forum C Programming
    Replies: 3
    Last Post: 03-27-2002, 06:58 PM
  5. Quick question: exit();
    By Cheeze-It in forum C Programming
    Replies: 6
    Last Post: 08-15-2001, 05:46 PM