Thread: Question... do/while loop

  1. #1
    Registered User
    Join Date
    Aug 2003

    Question... do/while loop

    I'm trying to make a loop that would only stop after a user has inputted a positive number, and would loop if a negative num or a char were typed in.

    printf ("Enter a Decimal number: ");
    scanf ("%d", &a);  
    	if (a > 0){
    		i = 1; /*'i' is sort of my 
    switch, changing its value breaks out of the loop*/
    		printf ("Invalid Decimal number \n");
    }while (i == 0); /*if anyone can suggest a 
    better way of doing this, I'd appreciate it... */
    It seems to work fine on negative numbers, the user can try again, but it loops infinitely when put in a character...scan doesn't seem to work twice...

  2. #2
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    well two things, a char when read as an int is always positive, so if you put a char you program would exit, and you need to make flush the output, I would do this at the end of the loop
    while(getchar() != '\n')

    or I think this would work

  3. #3
    Registered User
    Join Date
    Nov 2002
    The trick I use with chars and ints is always:
    if((integer=atoi(chararray)) == 0)
        printf("user entered a string or 0\n");
    As you can see, if zero is also a possible true or necessary value, this would not work ... . Otherwise it works fine. The user can also enter a string with white-spaces, like
    "I am very stupid"
    The programm'd recognize this and prints out the error ... .

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. For loop question
    By JuzMe in forum C++ Programming
    Replies: 11
    Last Post: 04-20-2009, 08:39 AM
  2. Loop question
    By kwood965 in forum C Programming
    Replies: 6
    Last Post: 10-29-2008, 11:12 PM
  3. simple for loop function question
    By felicityxiv in forum C Programming
    Replies: 7
    Last Post: 05-06-2006, 11:43 PM
  4. Please don't laugh...SIMPLE loop question!
    By the_lumin8or in forum C++ Programming
    Replies: 5
    Last Post: 03-31-2006, 01:08 PM
  5. for loop question
    By cdalten in forum C Programming
    Replies: 4
    Last Post: 03-20-2006, 09:42 AM