loop

This is a discussion on loop within the C Programming forums, part of the General Programming Boards category; Is it possible to create a do-while loop to restrict input to numbers only and not letters?...

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    19

    loop

    Is it possible to create a do-while loop to restrict input to numbers only and not letters?

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Yes. FAQ
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Feb 2006
    Posts
    19
    I looked into this and understand that it is the getchar command. But I have tried several ways of doing it but cannot seem to get it to work right. I have a program that is supposed to accept numbers until a negative number is inputed and then it will ask to average the numbers, or exit. I put a letter in and it crashes. Cannot figure out how to change my "scanf" command to the "getchar" command to make it take only numbers. Let me know if the code needs to be posted or if it is more proper here to email it.

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    Quote Originally Posted by rculley1970
    Let me know if the code needs to be posted or if it is more proper here to email it.
    The code needs to be posted; you should not email it.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  5. #5
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,075
    Though only post the part that pertains to the topic. That includes declarations and the last assignment of any variables that exist in that scope.
    Sent from my iPadŽ

  6. #6
    Registered User
    Join Date
    Feb 2006
    Posts
    19
    This program is for a class so I do not want the exact answer. I would greatly appreciate a nudge in the right direction though. I have tried to put the "getchar" command in but had no success. this is just a snippet of the original code with the "scanf" command.

    Code:
    float n, count = 0, average = 0, sum = 0;
    	int op;
    	printf("This program asks the user to input a series of test scores\n");
    		printf("and tells the user whether the grades are PASSING or FAILING.\n");
    		printf("Next, the user can select from other menu options that will\n");
    		printf("allow additional grade queries or allow the user to exit from\n");
    		printf("the program.\n\n");
    	printf("Please enter test scores.  After each score, press the return key.\n");
    		printf("When you are finished entering scores please enter a negative number.\n\n");
    	scanf("%f", &n);
    	while (n >= 0)
    	{
    		++count;
    	sum += n;
    	scanf("%f", &n);
    	}
    	average = sum / count;
    	printf("\n");
    	if (average >= 60.0)
    		printf("****PASSING****\n\n\n");
    	else
    		printf("****FAILING****\n\n\n");

  7. #7
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,764
    It takes a lot of code to make scanf() bomb-proof against erroneous user input. As you've probably seen, entering characters to that loop causes it to loop indefinitely.

    This approach is generally a lot simpler to get right, because it separates input from conversion.
    Code:
    char buff[100];
    while ( fgets( buff, sizeof buff, stdin ) != NULL ) {
      if ( sscanf( buff, "%f", &n ) == 1 ) {
        if ( n >= 0 ) {
          sum += n;
          count++;
        } else {
          // end of input signalled
          break;
        }
      } else {
        // not a float, complain
      }
    }

  8. #8
    Registered User
    Join Date
    Feb 2006
    Posts
    19
    That is quite advanced to what I should be using right now. As far as I was told by one instructer, I should be using the 'getchar' command. Isn't there are more simple way of doing this?

  9. #9
    old man
    Join Date
    Dec 2005
    Posts
    90
    You can approximate fgets() with something like the following:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int
    main (void)
    {
      int i, ch;  char buf[128];
    
      printf ("\nEnter a number > ");
      for (i = 0; (ch = getchar()) != '\n'; i++)
        buf[i] = ch;
      buf[i] = '\0';
    
      printf ("You entered %.2f\n\n", atof (buf));
      return 0;
    }
    edit: there's no check for buffer overrun here; this is just a very simple example ...

    For your specific purposes, you can either grab the input string and examine it, or you can check as you grab each digit ... I think that's enough information, since you only want hints ;-)
    Last edited by eerok; 02-26-2006 at 12:14 PM.

  10. #10
    Registered User
    Join Date
    Feb 2006
    Posts
    19
    that code only displays the number you type in. if you type in a letter, it will only show 0.00 and end the program. If you look at the original code I posted, you will see that it is an infinite loop if a letter is typed in. I am trying to use the 'getchar' command to prevent this from happening. So I am pretty much looking at an additional loop inside a loop.

  11. #11
    old man
    Join Date
    Dec 2005
    Posts
    90
    You said you didn't want the exact answer, so I didn't write your program for you.

    You can simply check the input inside the getchar() loop with isdigit() or whatever you like.

  12. #12
    Registered User
    Join Date
    Feb 2006
    Posts
    19
    FINALLY figured it out. but it sorta messed up some other function within the program. I was able to put things into a do-while loop with 'getchar'. still working on it. Didn't have to use 'isdigit()'. I appreciate everyones help. Thank you and should have it done soon. Will post it after tomorrow since it is due tomorrow. I just need to figure out the new bugs I created. It is supposed to average and count the number of grades entered but after solving the 'getchar' issue, it won't count or average right anymore.

  13. #13
    Registered User
    Join Date
    Feb 2006
    Posts
    19
    Is there something I am missing? I can't seem to find the issue.

    Code:
    float count, num, sum, average;
    	int n, op;
    	printf("please enter your numbers: \n");
    	
    	do {
    		
    		
    		//********************************
    		
    		
    		while (scanf("%f", &num) != 1)
    		{
    			while (getchar() != '\n');
    			printf ("Try again: \n");
    		}
    		
    		//********************************
    
    		++count;
    		sum += num;
    		//scanf("%f", &a);
    	}
    	
    	while (num >= 0);
    
    	
    	average = sum / count;
    	printf("average:  %.2f\n", average);
    	printf("sum:  %.2f\n", sum);
    	printf("count:  %.2f\n", count);

  14. #14
    Registered User
    Join Date
    Feb 2006
    Posts
    19
    Thank you for everyones help. I finally figured out all the bugs and got it working just right. And just in time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. nested loop, simple but i'm missing it
    By big_brother in forum C Programming
    Replies: 19
    Last Post: 10-23-2006, 11:21 PM
  2. While loop misbehaving (or misunderstanding)
    By mattAU in forum C Programming
    Replies: 2
    Last Post: 08-28-2006, 03:14 AM
  3. loop in a linked linked lists
    By kris.c in forum C Programming
    Replies: 6
    Last Post: 08-26-2006, 01:38 PM
  4. while loop help
    By bliznags in forum C Programming
    Replies: 5
    Last Post: 03-20-2005, 12:30 AM
  5. loop issues
    By kristy in forum C Programming
    Replies: 3
    Last Post: 03-05-2005, 09:14 AM

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