Thread: Using putchar to output an integer with more than 1 digit

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    7

    Using putchar to output an integer with more than 1 digit

    Hi, I'm trying to create a program that does simple C arithmetic calculations (such as 12 + 12). There can be multiple blanks before and after an operand. The expression and result and expression is supposed to be displayed like 12+12=24, where the expression (12+12) must be output from only using putchar. The = and result (24) can be used with a printf function, but anything dealing with the expression can not be used with printf (putchar only.) So far, I just want to know how I can store the operand (12 for example) and output it.

    Code:
    #include <stdio.h>
    
    int convert(void);
    
    int main(void)
    {
    	int op1;
    	op1 = convert();
    
    	printf("%d", op1);
    
    	return 0;
    
    }
    
    
    int convert(void)
    {
    	int iochar,
    		sum = 0;
    	while(((iochar = getchar() ) != ' ' ) && (iochar != '\n' ) )
    	{
    		sum = sum * 10 + (iochar - '0');
    	}
    	return (sum);
    }
    The code I have above was used mostly from a convert function from my programming book which reads from standard input until either a blank or end of line is found. It works, but only because printf function is being used in main. If I enter something such as putchar(op1); instead of printf("%d", op1);, I get some awkward results (symbols, alt codes, etc.) Any advice would be highly appreciated, I just want to know how I can store the integer (with more than 1 digit) using getchar and also output it using putchar. I've also tried tackling the problem with a different piece of code, but only the first number of the operand would be output (instead of 12, it would only output 1.)

  2. #2
    {Jaxom,Imriel,Liam}'s Dad Kennedy's Avatar
    Join Date
    Aug 2006
    Location
    Alabama
    Posts
    1,065
    Dup post: Mods, please delete.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help me please.
    By yann in forum C Programming
    Replies: 15
    Last Post: 09-29-2009, 09:04 PM
  2. Link List math
    By t014y in forum C Programming
    Replies: 17
    Last Post: 02-20-2009, 06:55 PM
  3. modifying help plz ( int to float )
    By sh4k3 in forum C Programming
    Replies: 11
    Last Post: 06-29-2007, 06:46 AM
  4. Putchar() to print an integer value?
    By swgh in forum C Programming
    Replies: 2
    Last Post: 05-19-2007, 12:30 PM
  5. 200 digit integer... how?
    By skeptik in forum C Programming
    Replies: 20
    Last Post: 07-25-2005, 07:56 AM