Question... do/while loop

This is a discussion on Question... do/while loop within the C Programming forums, part of the General Programming Boards category; I'm trying to make a loop that would only stop after a user has inputted a positive number, and would ...

  1. #1
    Registered User
    Join Date
    Aug 2003
    Posts
    2

    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.

    Code:
    do{
    
    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*/
    		}
    
    	else{
    		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
    Posts
    501
    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
    fflush(stdout);

  3. #3
    Registered User
    Join Date
    Nov 2002
    Posts
    34
    The trick I use with chars and ints is always:
    Code:
    scanf("%s[^\n]",chararray);
    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, 09:39 AM
  2. Loop question
    By kwood965 in forum C Programming
    Replies: 6
    Last Post: 10-30-2008, 12:12 AM
  3. simple for loop function question
    By felicityxiv in forum C Programming
    Replies: 7
    Last Post: 05-07-2006, 12:43 AM
  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

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