Integers trouble

This is a discussion on Integers trouble within the C Programming forums, part of the General Programming Boards category; Hi everyone, I'm writing a fairly simple application. Below is the part of the code that is giving me troubles. ...

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

    Integers trouble

    Hi everyone,

    I'm writing a fairly simple application. Below is the part of the code that is giving me troubles. The headers I have are:
    <stdio.h><stdlib.h><math.h>

    This is just one function of few. It is supposed to ask the user for an integer, check that it's an integer and return the value to the main function. However, whenever I enter an integer during runtime, it somehow gets a crazy value (ie. I enter 15, it gets 238 or something).

    Code:
    int read_int(void){
       int number=0;
       char c='';
       do{
    	c=getc(stdin);
    	if ((c!='1')&&(c!='2')&&(c!='3')&&(c!='4')&&(c!='5')&&(c!='6')&&(c!='7')&&(c!='8')&&(c!='9')&&(c!='0')&&(c!='\n')){
    	printf("Invalid input.\n");
    	exit(1);
    	}
    
    	if (c!='\n'){
    		number=number*10+atoi(&c);
    	}
       
       }while(c!='\n');
      
      return number;
    I'm not sure what's wrong with it... It has worked before at the university with a different compiler, but I don't know how that would make a difference. I'm using the same idea for another function and it works there. Any help would be greatly appreciated.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Only 238? You should call yourself lucky. atoi takes a string as input, and you don't have one. If you want to convert a single character to a number, you need to use
    Code:
    c-'0'

  3. #3
    Registered User
    Join Date
    Sep 2009
    Posts
    2
    Wow, that was quick. Thanks so much!

    Is there a reason why it works with single characters in other cases though?

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,185
    Sheer blind luck. It should never work with a single character.

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, 05:55 PM
  2. Assignment HELP!!
    By cprogrammer22 in forum C Programming
    Replies: 35
    Last Post: 01-24-2009, 01:24 PM
  3. Integers into array.
    By livestrng in forum C Programming
    Replies: 10
    Last Post: 10-29-2008, 11:35 PM
  4. factor of integers trouble
    By surfingbum18 in forum C Programming
    Replies: 4
    Last Post: 09-27-2007, 01:35 AM
  5. Replies: 6
    Last Post: 08-04-2003, 10:57 AM

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