Returning from function - switch selects default

This is a discussion on Returning from function - switch selects default within the C Programming forums, part of the General Programming Boards category; Hi guys, I've been searching this forum and the FAQ for a solution for this problem but I can't find ...

  1. #1
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154

    Returning from function - switch selects default

    Hi guys,

    I've been searching this forum and the FAQ for a solution for this problem but I can't find anything that works. Either I'm not applying it in the right way, or the solution is simply not on the forum yet.
    Hope you can help me out. I call a filecopy function by using a switch menu. Now when Im finished copying the file it returns to the switch menu. Problem is that when it comes back to the switch menu, it automatically activates the default option (which I defined as closing the application). Now after reading here and there I think the input buffer is not yet empty when I get back to the menu, though I have no idea how to correct this. I've tried fflush but that didn't change anything. Also I've tried using fgets() instead of scanf() in my file copy function though then my program isn't able to open the filename I enter.

    Hope that's clear enough, here are the code snippets:

    The file copy function:
    Code:
    int analyse_data(void)
    {
       FILE *fpin, *fpout;
       char flin[256],flout[256];
       int ih;
       
       clrscr();
       puts(program_title);    
       puts(break_line);
       
       puts(source_file);
    //   fgets(flin, sizeof(flin), stdin);
       scanf("%s",flin);   
    //   flin[strlen(flin)-1]='\0'; // delete \n
       if((fpin = fopen(flin, "rb"))== NULL)
       {
          puts(source_file_error);
          return 0;
       }
       
       puts(destination_file);
       scanf("%s",flout);
    //   fgets(flout, sizeof(flout), stdin);
       fpout=fopen(flout,"wb");
       while((ih=fgetc(fpin))!=EOF)
       {
          fputc(ih,fpout);
      	  putch(ih);
       }
       
       fclose(fpin);
       fclose(fpout);
    
       return 0;
    }
    The menu in main:
    Code:
        switch(menu_switch)
        {
            case 1:
                 exit_flag=FALSE;  
                 test_procedure();
                 getch();
                 clrscr();
            break;
            
            case 2:
                 exit_flag=FALSE;
    //             puts("You chose 2");
                 analyse_data();
                 getch();
                 clrscr();
            break;
            
            case 3:
                 exit_flag=FALSE;
                 puts("You chose 3");
                 getch();             
                 clrscr();
            break;
            
            case 4:
                 exit_flag=TRUE;
            break;
            
            default: exit_flag=TRUE;
        }
    }
    while(exit_flag==FALSE);
    You'll probably be able to see from the code that I'm not an expert programmer yet. Off topic tips are always welcome

    Thanks a lot in advance, René
    Last edited by rkooij; 03-08-2006 at 03:41 AM.

  2. #2
    Registered User
    Join Date
    Feb 2006
    Posts
    155
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    
    int analyse_data(void)
    {
       FILE *fpin, *fpout;
       char flin[256],flout[256];
       int ih;
       
    
       puts("program_title");    
       puts("break_line");
       
       puts("source_file");
    //   fgets(flin, sizeof(flin), stdin);
       scanf("%s",flin);   
    //   flin[strlen(flin)-1]='\0'; // delete \n
       if((fpin = fopen(flin, "rb"))== NULL)
       {
          puts("source_file_error");
          getch();
          return 0;
       }
       
       puts("destination_file");
       scanf("%s",flout);
    //   fgets(flout, sizeof(flout), stdin);
       fpout=fopen(flout,"wb");
       while((ih=fgetc(fpin))!=EOF)
       {
          fputc(ih,fpout);
      	  putch(ih);
       }
       
       fclose(fpin);
       fclose(fpout);
    
       return 0;
    }
    
    main(){
    int a,exit_flag;
    do{
    
    printf("enter a value:");
    scanf("%d",&a);
       switch(a)
        {
            case 1:
                 exit_flag=1;  
            
                 getch();
              
            break;
            
            case 2:
                 exit_flag=1;
                puts("You chose 2");
                 analyse_data();
                 getch();
               
            break;
            
            case 3:
                 exit_flag=1;
                 puts("You chose 3");
                 getch();             
                
            break;
            
             case 4:
                 exit_flag=0;
            break;
            
            default: exit_flag=0;
        }
    }
    while(exit_flag);
    
    
    }
    i dont know why u r complaining,it is working just fine,but too many unnecessary getch().

  3. #3
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    i dont know why u r complaining,it is working just fine,but too many unnecessary getch().

    Yeah I noticed I had one getch() too much, cos I was playing around with that and I forgot to delete it afterwards (edited it in my post before you replied anyway ).

    I'm sorry but I still have the problem. When I come back from the analyse_data() function, it doesn't allow me to choose a menu item by entering a number. It just immediately jumps to puts(close_window)....

    Edit: copied and compiled your code above and that does work. Must be something else then... Here's the complete main, hope that helps.

    Edit: deleted, full code a couple of posts below.

    Thanks for your effort.
    Last edited by rkooij; 03-08-2006 at 04:51 AM.

  4. #4
    Registered User
    Join Date
    Feb 2006
    Posts
    155
    i tried running this ,it is running too,but i disabled sleep and clrscr and fullscreen cuz my compiler doesnt support these.
    i have no clue what these functions do to the input stream,anyways try flushing the input stream after u use them.
    Last edited by qqqqxxxx; 03-08-2006 at 04:26 AM.

  5. #5
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Quote Originally Posted by qqqqxxxx
    i tried running this ,it is running too,but i disabled sleep and clrscr and fullscreen cuz my compiler doesnt support these.
    i have no clue what these functions do to the input stream,anyways try flushing the input stream after u use them.
    Ok, thank you. I've tried without those functions (full_screen, sleep and clrscr) but that doesn't change anything.

    Could you please give me an example of how to apply flush to this input stream? I've been trying loads of times with various examples I found, though nothing seems to work.




    Oh btw, off topic: Sleep is from <windows.h> and I defined clrscr() before main:
    Code:
    void clrscr(void)
    {
        COORD                       coordScreen = { 0, 0 };
        DWORD                       cCharsWritten;
        CONSOLE_SCREEN_BUFFER_INFO  csbi;
        DWORD                       dwConSize;
        HANDLE                      hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
        GetConsoleScreenBufferInfo(hConsole, &csbi);
        dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
        FillConsoleOutputCharacter(hConsole, TEXT(' '), 
                                   dwConSize, coordScreen, &cCharsWritten);
        GetConsoleScreenBufferInfo(hConsole, &csbi);
        FillConsoleOutputAttribute(hConsole, csbi.wAttributes, 
                                   dwConSize, coordScreen, &cCharsWritten);
        SetConsoleCursorPosition(hConsole, coordScreen);
    }
    Think this function is Windows only btw (?). Thought you might wanted to know.
    Last edited by rkooij; 03-08-2006 at 04:37 AM.

  6. #6
    Registered User
    Join Date
    Feb 2006
    Posts
    155
    can u give the full code,the code which u r trying to run,exact copy?

  7. #7
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    I can, hang on.

    Code:
    /************************************/
    /*       CAN Diagnosis system       */
    /*        René van der Kooij        */
    /************************************/
    
    #include <stdio.h>
    #include <conio.h>
    #include <time.h>
    #include <stdint.h>
    #include <stdlib.h>
    #include <string.h>
    #include <windows.h>
    
    #define choose_menu                   "Please enter a number:"
    #define title_vehicle_make            "Please enter the vehicle make: "
    #define title_vehicle_model           "Please enter the vehicle model: "
    #define title_vehicle_year            "Please enter the model year: "
    #define title_vehicle_chassisnumber   "Please enter the chassis number: "
    #define title_vehicle_tester          "Please enter the vehicle tester: "
    #define title_test_location           "Please enter the location of the test: "
    #define title_general_info            "   General test information:   [1/2]"
    #define title_can_info                "   CAN information:            [2/2]"
    #define title_main_menu               "   MAIN MENU"
    #define title_can_baudrate            "Please enter the CAN baudrate: "
    #define title_can_location            "Please enter the location of the CAN connector: "
    #define title_info_file               "***** Test info file *****\n"
    #define program_title                 "\n[           CAN Diagnosis          ]"
    #define break_line                    "------------------------------------"
    #define main_menu1                    "1. Start test procedure"
    #define main_menu2                    "2. Analyse data"
    #define main_menu3                    "3. Placeholder"
    #define main_menu4                    "4. Exit"
    #define close_window                  "[  Press any key to close window  ]"
    #define invalid_entry                 "Invalid entry! Please try again"
    #define source_file                   "Please enter the source filename:"
    #define source_file_error             "Can't open source file!"
    #define destination_file              "Please enter the destination filename:"
    
    /****************************** Global Variables ******************************/
    FILE *test_info, *CAN_data;
    char info_filename[30], data_filename[30], year[30];
    char vehicle_make[80], vehicle_model[80], vehicle_year[80], vehicle_chassisnumber[80], vehicle_tester[80], test_location[80], can_baudrate[80], can_location[80], length;
    time_t now, rawtime;
    bool exit_flag, error_flag=FALSE;
    
    
    
    
    /***************************** Fullscreen function ****************************/
    void full_screen(void)
    {
        keybd_event(VK_MENU,0x38,0,0);
        keybd_event(VK_RETURN,0x1c,0,0);
        keybd_event(VK_RETURN,0x1c,KEYEVENTF_KEYUP,0);
        keybd_event(VK_MENU,0x38,KEYEVENTF_KEYUP,0);
    }
    // MS Windows only (?)
    
    
    
    
    /************************ Function to clear the screen ************************/
    void clrscr(void)
    {
        COORD                       coordScreen = { 0, 0 };
        DWORD                       cCharsWritten;
        CONSOLE_SCREEN_BUFFER_INFO  csbi;
        DWORD                       dwConSize;
        HANDLE                      hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
        GetConsoleScreenBufferInfo(hConsole, &csbi);
        dwConSize = csbi.dwSize.X * csbi.dwSize.Y;
        FillConsoleOutputCharacter(hConsole, TEXT(' '), 
                                   dwConSize, coordScreen, &cCharsWritten);
        GetConsoleScreenBufferInfo(hConsole, &csbi);
        FillConsoleOutputAttribute(hConsole, csbi.wAttributes, 
                                   dwConSize, coordScreen, &cCharsWritten);
        SetConsoleCursorPosition(hConsole, coordScreen);
    }
    // MS Windows only (?)
    
    
    
    
    /**************************** Analyse data function ***************************/
    int analyse_data(void)
    {
       FILE *fpin, *fpout;
       char flin[256],flout[256];
       int ih;
       
    //   clrscr(); //Clear screen, MS Windows only (?)
       puts(program_title);    
       puts(break_line);
       
       puts(source_file);
    //   fgets(flin, sizeof(flin), stdin);
       scanf("%s",flin);   
    //   flin[strlen(flin)-1]='\0'; // delete \n
       if((fpin = fopen(flin, "rb"))== NULL)
       {
          puts(source_file_error);
          getch();
          return 0;
       }
       
       puts(destination_file);
       scanf("%s",flout);
    //   fgets(flout, sizeof(flout), stdin);
       fpout=fopen(flout,"wb");
       while((ih=fgetc(fpin))!=EOF)
       {
          fputc(ih,fpout);
      	  putch(ih);
       }
       
       fclose(fpin);
       fclose(fpout);
    
       return 0;
    }
    
    
    
    /*************************** Test procedure function **************************/
    void test_procedure(void)
    {
    //    clrscr(); //Clear screen, MS Windows only (?)
        puts(program_title);
        
        /* Time Function for display in log file and interface */
        struct tm * timeinfo;
        time (&rawtime);
        timeinfo = localtime (&rawtime);
        /*******************************************************/
        
        
        /* Time function for filename definition */    
        now = time(NULL);
        struct tm *t = localtime(&now);
        /*****************************************/
        
        
        /* Input request */
        puts(break_line);
        puts(title_general_info);
        puts(break_line);
            
        /* Vehicle make */
        while(strlen(vehicle_make)<2)
        {
           puts(title_vehicle_make);
           fgets(vehicle_make, 80, stdin);
           if(strlen(vehicle_make)<2)
           {
              puts(invalid_entry);
    //          Sleep(500);
           }
        }
        vehicle_make[ strcspn( vehicle_make, "\n" ) ] = '\0';
    //    vehicle_make[strlen(vehicle_make)-1]='\0'; // delete \n
    
        /* Vehicle year */
        while(strlen(vehicle_model)<2)
        {
           puts(title_vehicle_model);
           fgets(vehicle_model, 80, stdin);
           if(strlen(vehicle_model)<2)
           {
              puts(invalid_entry);
    //          Sleep(500);
           }
        }
        vehicle_model[ strcspn( vehicle_model, "\n" ) ] = '\0';
    //    vehicle_model[strlen(vehicle_model)-1]='\0'; // delete \n
    
        while(strlen(vehicle_year)<2)
        {
           puts(title_vehicle_year);
           fgets(vehicle_year, 80, stdin);
           if(strlen(vehicle_year)<2)
           {
              puts(invalid_entry);
    //          Sleep(500);
           }
        }
        vehicle_year[ strcspn( vehicle_year, "\n" ) ] = '\0';
    //    vehicle_year[strlen(vehicle_year)-1]='\0'; // delete \n
    
        /* Chassis number */
        while(strlen(vehicle_chassisnumber)<2)
        {
           puts(title_vehicle_chassisnumber);
           fgets(vehicle_chassisnumber, 80, stdin);
           if(strlen(vehicle_chassisnumber)<2)
           {
               puts(invalid_entry);
    //           Sleep(500);
           }
        }
        vehicle_chassisnumber[ strcspn( vehicle_chassisnumber, "\n" ) ] = '\0';
    //    vehicle_chassisnumber[strlen(vehicle_chassisnumber)-1]='\0'; // delete \n
        
        /* Vehicle tester */
        while(strlen(vehicle_tester)<2)
        {
           puts(title_vehicle_tester);
           fgets(vehicle_tester, 80, stdin);
           if(strlen(vehicle_tester)<2)
           {
               puts(invalid_entry);
    //           Sleep(500);
           }
        }
        vehicle_tester[ strcspn( vehicle_tester, "\n" ) ] = '\0';
    //    vehicle_tester[strlen(vehicle_tester)-1]='\0'; // delete \n
        
        /* Test location */
        while(strlen(test_location)<2)
        {
           puts(title_test_location);
           fgets(test_location, 80, stdin);
           if(strlen(test_location)<2)
           {
               puts(invalid_entry);
    //           Sleep(500);
           }
        }
        test_location[ strcspn( test_location, "\n" ) ] = '\0';
    //    test_location[strlen(test_location)-1]='\0'; // delete \n
        
    //    clrscr();//Clear screen
        puts(program_title);
        puts(break_line);    
        puts(title_can_info);
        puts(break_line);
            
        /* CAN baudrate */
        while(strlen(can_baudrate)<2)
        {
           puts(title_can_baudrate);
           fgets(can_baudrate, 80, stdin);
           if(strlen(can_baudrate)<2)
           {
               puts(invalid_entry);
    //           Sleep(500);
           }
        }
        can_baudrate[ strcspn( can_baudrate, "\n" ) ] = '\0';
    //    can_baudrate[strlen(can_baudrate)-1]='\0'; // delete \n
    
        /* CAN location */
        while(strlen(can_location)<2)
        {
           puts(title_can_location);
           fgets(can_location, 80, stdin);
           if(strlen(can_location)<2)
           {
               puts(invalid_entry);
    //           Sleep(500);
           }
        }
        can_location[ strcspn( can_location, "\n" ) ] = '\0';    
    //    can_location[strlen(can_location)-1]='\0'; // delete \n
    
        puts(break_line);
        
        
        strftime(info_filename, sizeof(info_filename), "i_%d%m%y_%H%M%S.txt", t);
        strftime(data_filename, sizeof(data_filename), "d_%d%m%y_%H%M%S.txt", t);
    //    strftime(year, sizeof(year), "%Y", t);
        
        /* Create test info file */
        test_info = fopen(info_filename, "w");
        fprintf(test_info, title_info_file);
        fprintf(test_info, asctime (timeinfo));
        fprintf(test_info, "\nmake: %s\nmodel: %s\nyear: %s\nchassis number: %s\ntester: %s\ntest location: %s\ncan baudrate: %s\ncan connector location: %s", vehicle_make, vehicle_model, vehicle_year, vehicle_chassisnumber, vehicle_tester, test_location, can_baudrate, can_location);
        fclose(test_info);
        printf("Info file (%s) created successfully!\n", info_filename);
        /*************************/
    
    //    Sleep(1000); //Wait to display info file name
    //    clrscr(); //Clear screen, MS Windows only (?)
    
        puts(program_title);
        
        /* Create CAN data file */
        CAN_data = fopen(data_filename, "w");
        
        
        
    //    fprintf(CAN_data, "This is the placeholder for CAN data extracted from the %s %s network", vehicle_make, vehicle_model);
        
        /* Close CAN data file */
        fclose(CAN_data);
    
        printf("\nData file (%s) created successfully!\n", data_filename);
    }
    
    
    
    
    
    
    /*********************************** MAIN *************************************/
    
     int main(void)
    
    {
        /* Define variables */
        char buf[BUFSIZ];
        int menu_switch=0;
    
        /* Start full screen */
    //    full_screen();
        
        /* One second pause to prevent double filenames */
    //    Sleep(1000);
        // MS Windows only (?)
    
    /* Start of actual program */
    do
    {
        puts(program_title);
        puts(break_line);
        puts(title_main_menu);    
        puts(break_line);
        /* Test menu */
    
        puts(main_menu1);
        puts(main_menu2);    
        puts(main_menu3);
        puts(main_menu4);
        puts(break_line);
        puts(choose_menu);
    
        /* Get user input for function selection */
        if (fgets(buf, sizeof(buf), stdin) != NULL)
        {
          menu_switch = atoi(buf);
        }
    
        switch(menu_switch)
        {
            case 1:
                 exit_flag=1;  
            
                 getch();
              
            break;
            
            case 2:
                 exit_flag=1;
                puts("You chose 2");
                 analyse_data();
                 getch();
               
            break;
            
            case 3:
                 exit_flag=1;
                 puts("You chose 3");
                 getch();             
                
            break;
            
             case 4:
                 exit_flag=0;
            break;
            
            default: exit_flag=0;
        }
    }
    while(exit_flag);
    
    
    
    
        
    
        puts(close_window);
        getch();
        
    return 0;
    }
    /******************************************************************************/

  8. #8
    Registered User
    Join Date
    Feb 2006
    Posts
    155
    Do U Honestly Think I Am Going To Read All That?

  9. #9
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Quote Originally Posted by qqqqxxxx
    Do U Honestly Think I Am Going To Read All That?
    Hahahaha! You asked for it!!

    Edit: could you just give me an example how to flush the input please? So I can try that first..?

  10. #10
    Registered User
    Join Date
    Feb 2006
    Posts
    155
    fflush(stdin);

  11. #11
    Registered User
    Join Date
    Feb 2006
    Posts
    155
    and i tried running your program,it runs fine if u remove the default case.

  12. #12
    cwr
    cwr is offline
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Quote Originally Posted by qqqqxxxx
    fflush(stdin);
    Why fflush(stdin) is wrong.

  13. #13
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Quote Originally Posted by qqqqxxxx
    fflush(stdin);
    Errrmm... that works.... .
    For some dumb reason I always tried fflush(stdout); Just because I didn't have a clue how it works! This seems obvious though...

    Thanks man!

    Edit: DAMN, always when things seem to work I hear that it's not right...
    Last edited by rkooij; 03-08-2006 at 05:05 AM.

  14. #14
    cwr
    cwr is offline
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    rkooij,

    fflush(stdin) is totally wrong, did you read the link i posted above?

    Even if it works, it's wrong.

  15. #15
    1ST » R. vd Kooij
    Join Date
    Mar 2006
    Location
    Netherlands
    Posts
    154
    Quote Originally Posted by qqqqxxxx
    and i tried running your program,it runs fine if u remove the default case.
    Yeah, I have been thinking about removing the default case, though that would mean I didn't learn anything, just how to avoid trouble in a lame way

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  2. Recursion: base case returning 1, function returning 0
    By yougene in forum C Programming
    Replies: 5
    Last Post: 09-07-2007, 06:38 PM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 03:39 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 07:39 AM
  5. Replies: 5
    Last Post: 02-08-2003, 07:42 PM

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