Help with input flush

This is a discussion on Help with input flush within the C Programming forums, part of the General Programming Boards category; I've been browsing through some threads on this board and I ventured to a section in the faq about input ...

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    13

    Help with input flush

    I've been browsing through some threads on this board and I ventured to a section in the faq about input flush. This topic interests me because I was having some trouble with validating user input. The section of code in the faq, however, will not work with my compiler. I was wondering if there were any alternatives to this. I will post the flush code first, and then my program I am working on. I am also using the crappy Miricle C complier.

    Code:
    #include <stdio.h> 
    
    int main(void)
    {
      int   ch;
      char  buf[BUFSIZ];
      
      puts("Flushing input");
      
      while ((ch = getchar()) != '\n' && ch != EOF);
      
      printf ("Enter some text: ");
      
      if (fgets(buf, sizeof(buf), stdin))
      {
        printf ("You entered: %s", buf);
      }
      
      return 0;
    }
    This is the error I get: Parse Error, expecting `']'' or `NUMBER'
    'char buf[BUFSIZ]'

    Here is my code that I am working on
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
        int main(void)// main funtion with no parameters
        
         {
             int i = 0;
             char cArray[5][15] = { "1  Aus dollar", "2  Can dollar", "3  Euro", "4  Mex peso", "5  Swiss franc"};
             char iSelection = '\0'; //initializes the menu selection
             float fCurrSelect = 0.00; //initializes the monetary value to be converted
             float fUSCurr = 0.00; //initializes the currency conversion
             
             do {
                //displays the title for program    
                printf("\n\tCurrency Conversion Program 1.1\n\n");
                printf("\nChoose the currency you wish to convert\n");
                
               for (i=0; i<5; i++)
                   printf("\n%s", cArray[i]);
                   printf("\n\n");
                   scanf("%c", &iSelection); //stores the menu selection for conversion        
                
                }while ( iSelection < '1' || iSelection > '5');//checks for valid input
                              
                      
             do {
                
                printf("\nHow much money would you like to convert to U.S. dollars?");
                scanf("%f", &fCurrSelect);
             
             }while (fCurrSelect <= 0.0);//checks for valid currency amount
             
             //this begins the case switch for the menu selection            
             switch(iSelection) { 
                
                   case '1':
                   fUSCurr = (fCurrSelect/1.16686);
                   printf("\nThe Austrailian dollar amount %.2f converted to USD equals $%.2f", fCurrSelect, fUSCurr);
                   break;
                   
                   case '2':
                   fUSCurr = (fCurrSelect/1.0072);
                   printf("\nThe Canadian dollar amount %.2f converted to USD equals $%.2f", fCurrSelect, fUSCurr);
                   break;
                   
                   case '3':
                   fUSCurr = (fCurrSelect/0.695943);
                   printf("\nThe Euro amount %.2f converted to USD equals $%.2f", fCurrSelect, fUSCurr);
                   break;
                   
                   case '4':
                   fUSCurr = (fCurrSelect/10.8509);
                   printf("\nThe Mexican peso amount %.2f converted to USD equals $%.2f", fCurrSelect, fUSCurr);
                   break;
                   
                   case '5':
                   fUSCurr = (fCurrSelect/1.1522);
                   printf("\nThe Swiss franc amount %.2f converted to USD equals $%.2f", fCurrSelect, fUSCurr);
                   break;
                   
                   default:
                   printf("\nInvalid option!");
                   
                }//end switch block
                getchar();
                return 0;
          }//end main

  2. #2
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,682
    Code:
    while ((ch = getchar()) != '\n' && ch != EOF);
    Why are you calling the fflush routine before you get the value from the user. It is normally called after reading the value from the user and to clear the '\n' char from the input buffer. Calling it in before hand will expect an enter char before it can follow though , which eventually has halted your program at some point.

    And by the way your code works fine on my machine. With no errors.

    ssharish

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >I am also using the crappy Miricle C complier.
    That's your problem. Miracle C is horribly broken.
    My best code is written with the delete key.

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    13
    Quote Originally Posted by ssharish2005 View Post
    Code:
    while ((ch = getchar()) != '\n' && ch != EOF);
    Why are you calling the fflush routine before you get the value from the user. It is normally called after reading the value from the user and to clear the '\n' char from the input buffer. Calling it in before hand will expect an enter char before it can follow though , which eventually has halted your program at some point.

    And by the way your code works fine on my machine. With no errors.

    ssharish
    That is the code that I found from this websites faq, describing how to properly flush the user input. I have no idea works, so I figured I would try it out and see what I could come up with. Then I couldn't get it to work with my compiler, which is garbage.

    The problem with my code is that if you enter multiple letters or digits you get some problems, so I thought that a flush would be a good idea to help with this. Also, when an invalid menu selection is made, the program loops twice, which I was told was because there is a \n in the scanf function.

    Anyways, I don't think it is really necessary to have this in my program because we haven't even come close to learning about any of these concepts. I'm the kind of person that likes to have things working the right way, so I am kind getting way ahead of myself. I really appreciate all the help you guys have given me. I would try doing my programming with a different compiler, but everyone in the class pretty much uses Miricle C, so no one would be able to compile half the stuff I would do

  5. #5
    Aia
    Aia is offline
    Beautiful to C Aia's Avatar
    Join Date
    Jun 2007
    Posts
    124
    >I have no idea works

    Code:
    while ((ch = getchar()) != '\n' && ch != EOF);
    getchar() returns a character from the standard input stream which gets stored in ch. While loop checks that ch is not a new line character nor the End Of File. Ensuring that it will keep reading anything in the buffer ( stdin ) until encounters this condition.

    You can use this routine every time your code needs to clear the stream of undesired left behind characters. Otherwise, don't apply it, since it will required the user to enter some input.

    Here's an example how you could obtain text input from user; making sure that:
    1st Input has been entered.
    2st String is of the right length.
    3rd The newline is removed from string if is there.
    4rd Any extra entered by user is discarded and cleared from buffer, ensuring new calls to read from stdin will be correct.

    Code:
    #include <stdio.h> 
    #include <string.h>
    
    int main( void )
    {
        char  buf[BUFSIZ] = { '\0' };   /* Set every element to null */
      
        printf ( "Enter some text: " ); /* Keeping prompt score at end of string */
        fflush( stdout );               /* correct use of fflush function */
        
        /* Get input from user */  
        if ( fgets( buf, sizeof buf , stdin ) != NULL )
        {
            size_t len = strlen( buf ) - 1; /* obtain possible position of '\n' */
            if ( buf[ len ] == '\n' )      /* find newline */
            {
                buf[ len ] = '\0';         /* remove newline */
            }
            else  
            {
                int ch;
                /* garbage collector */
                while ( ( ch = getchar() ) != '\n' && ch != EOF );
            }
            
            printf ( "You entered: &#37;s", buf );
        }
        /* here's the test: if the program doesn't pause, extra was left behind */
        getchar(); /* guinea pig */
        return 0;
    }

  6. #6
    Registered User
    Join Date
    Dec 2007
    Posts
    13
    Man, I swear that Miricle C is useless. I can't seem to compile your code Aia. Your explaination of what getchar is actually doing really helped out a lot. Another thing that I would like to learn more about is EOF, but Miricle C does not recognize EOF for some reason. I found this out when trying some examples from other tutorial sites.

    It is starting to get really frustrating with this outdated and broken compiler that they want us to use for our class. I feel like my programming potential is being governed by this lacking compiler. Is there a decent C compiler out there that you guys would recommend?

  7. #7
    Aia
    Aia is offline
    Beautiful to C Aia's Avatar
    Join Date
    Jun 2007
    Posts
    124
    Quote Originally Posted by KarrieWojo View Post
    Is there a decent C compiler out there that you guys would recommend?
    Yes there's many decent C compilers.
    For easy of use try this one.

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,852
    > It is starting to get really frustrating with this outdated and broken compiler that they
    > want us to use for our class.
    *boggle*, they're using that PoS in a class????
    What makes it worse is that it's nagware, and the author expects a payment, now that's a miracle indeed!.

    If you can't get your tutor to see the light (just show them several trivial programs which work with ANY other compiler, yet cause MC to puke), then you may be better off not being in that class at all. As you say, it's one big frustration fest getting MC to do anything.

    Even crusty old Turbo C wipes the floor with Miracle C.

    Here are many others (all free).
    http://www.thefreecountry.com/compilers/cpp.shtml
    http://www.compilers.net/Dir/Free/Compilers/CCpp.htm
    Also consider http://www.codeblocks.org/ as the successor to dev-c++.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  9. #9
    Registered User
    Join Date
    Dec 2007
    Posts
    13
    Thanks a bunch guys, I will definitely try out some of these comilers that you have listed. I'm just tired of reading through tutorials and then seeing a section of code I want to try out, and then not being able to try it because my compiler can't handle it.

    I will post back to let you guys know how things are going

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868

    Even crusty old Turbo C wipes the floor with Miracle C.
    Yur darn right!

  11. #11
    Registered User
    Join Date
    Dec 2007
    Posts
    13
    Hey guys, I've been working with my program some and I am pretty close to getting my function to work. It runs through fine, but it doesn't do the calculation. I have a feeling like it is something really small, but I can't seem to figure out where I went wrong. If anyone has a quick sec to take a look I would greatly appreciate it.

    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    #define AUS 1.16686
    #define CAN 1.0072
    #define EURO 0.695943
    #define MEX 10.8509
    #define SWISS 1.1522
    
    float conCal(char, float);//function prototype for calculation
    
    int main(void)// main funtion with no parameters
    
    {
            //array for the menu selection
            char cArray[5][15] = { "1  Aus dollar", "2  Can dollar", "3  Euro", "4  Mex peso", "5  Swiss franc"};
            char iSelection = '\0'; //initializes the menu selection
            float fCurrSelect = 0.00; //initializes the monetary value to be converted
            float conversion; //initializes the currency conversion
        	char c;
            int i = 0;
                    
                    printf("\n\tCurrency Conversion Program 1.1\n\n");
          
            while(1)
            {
                    //displays the title for program    
                    printf("\nChoose the currency you wish to convert\n");
    
                    for (i=0; i<5; i++)
                            printf("\n%s", cArray[i]);
                    printf("\n\nChoose an option: ");
                           
    
                    //ensures the menu selection is valid
                    while((c = getchar())!='\n')
                    {
                            iSelection = c;
                    }
    
                    if(iSelection < '1' || iSelection > '5')
                    {
                            printf("\n\nInvalid option...\n\n");
                            continue;
                    }
                    else
                    {
                            break;
                    }
            }//end while block 
    
            do {
            conCal(iSelection, fCurrSelect);
                    printf("\nHow much money would you like to convert to U.S. dollars?");
                    scanf("%f", &fCurrSelect);
    
            }while (fCurrSelect <= 0.0);//checks for valid currency amount
            
                printf("\nThe conversion to U.S. dollars is $%.2f",conversion);
                return 0;
                getchar();
            }//end main
    
            //function definition for conversion           
            float conCal(char iSelection, float fCurrSelect)
           {
           //local variable for conversion
           float conversion;
           //switch to user the case selected by user in reference funtion
           switch (iSelection)
           {
              case 1:
                   conversion=AUS/fCurrSelect;
                   break;
              case 2:
                   conversion=CAN/fCurrSelect;
                   break;
              case 3:
                   conversion=EURO/fCurrSelect;
                   break;
              case 4:
                   conversion=MEX/fCurrSelect;
                   break;
              case 5:
                   conversion=SWISS/fCurrSelect;
                   break;
         }
    //returns the new value to the main function
    return conversion;
    }

  12. #12
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,274
    Quote Originally Posted by KarrieWojo View Post
    This is the error I get: Parse Error, expecting `']'' or `NUMBER'
    'char buf[BUFSIZ]'
    Defining BUFSIZ would help. (Your compiler is pretty weak.)

  13. #13
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,852
    First off, learn how to indent.
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    #define AUS 1.16686
    #define CAN 1.0072
    #define EURO 0.695943
    #define MEX 10.8509
    #define SWISS 1.1522
    
    float conCal(char, float);      //function prototype for calculation
    
    int main(void)                  // main funtion with no parameters
    {
        //array for the menu selection
        char cArray[5][15] =
            { "1  Aus dollar", 
              "2  Can dollar", 
              "3  Euro", 
              "4  Mex peso",
              "5  Swiss franc" };
        char iSelection = '\0';     //initializes the menu selection
        float fCurrSelect = 0.00;   //initializes the monetary value to be converted
        float conversion;           //initializes the currency conversion
        char c;
        int i = 0;
    
        printf("\n\tCurrency Conversion Program 1.1\n\n");
    
        while (1) {
            //displays the title for program    
            printf("\nChoose the currency you wish to convert\n");
    
            for (i = 0; i < 5; i++)
                printf("\n&#37;s", cArray[i]);
            printf("\n\nChoose an option: ");
    
    
            //ensures the menu selection is valid
            while ((c = getchar()) != '\n') {
                iSelection = c;
            }
    
            if (iSelection < '1' || iSelection > '5') {
                printf("\n\nInvalid option...\n\n");
                continue;
            } else {
                break;
            }
        }                           //end while block 
    
        do {
            conCal(iSelection, fCurrSelect);
            printf("\nHow much money would you like to convert to U.S. dollars?");
            scanf("%f", &fCurrSelect);
        } while (fCurrSelect <= 0.0); //checks for valid currency amount
    
        printf("\nThe conversion to U.S. dollars is $%.2f", conversion);
        return 0;
        getchar();
    }                               //end main
    
    //function definition for conversion           
    float conCal(char iSelection, float fCurrSelect)
    {
        //local variable for conversion
        float conversion;
        //switch to user the case selected by user in reference funtion
        switch (iSelection) {
        case 1:
            conversion = AUS / fCurrSelect;
            break;
        case 2:
            conversion = CAN / fCurrSelect;
            break;
        case 3:
            conversion = EURO / fCurrSelect;
            break;
        case 4:
            conversion = MEX / fCurrSelect;
            break;
        case 5:
            conversion = SWISS / fCurrSelect;
            break;
        }
    
        //returns the new value to the main function
        return conversion;
    }
    Problems in red.
    1. You call the function BEFORE you've read in some data from the user.
    2. You ignore the return result.

    As a result, you just print whatever junk is in the conversion variable.

    > float conversion; //initializes the currency conversion
    This comment is a lie, it is not initialised.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I would love some input on my BST tree.
    By StevenGarcia in forum C++ Programming
    Replies: 4
    Last Post: 01-15-2007, 01:22 AM
  2. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 04:42 PM
  3. Structure and Linked List User Input Question
    By kevndale79 in forum C Programming
    Replies: 16
    Last Post: 10-05-2006, 12:09 PM
  4. need help with some input
    By blindleaf in forum C Programming
    Replies: 2
    Last Post: 03-16-2003, 01:50 PM

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