Thread: Getchar() is ignored by my program

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    13

    Getchar() is ignored by my program

    Hi,

    I am testing a program where I am doing some FILE I/O manipulations. At the end of the program I use a getchar() just to leave the console open. However, the program ignores the getchar and closes the console at once (not leaving me observe the results).

    I am only putting the main.c. Sorry for the incomprehensible names of the variables

    Do you have any ideas?
    Thanks

    Code:
    int main(void)
    {
    	int sfalma;
    	typos_stoivas stoiva; //stoiva twn orwn
    	float oros1,oros2,apotelesma;
    	char symbolo, apantisi, metathematiki[256];
    	int i;
    
        FILE *fp;
    		
        if ( (fp=fopen("input.txt","r"))==NULL ) 
        {
          printf("Error opening file\n");
          exit(1);                                                                                          
        }  
        
        while (!feof(fp))	
         {	
    	   dimiourgia(&stoiva);
    	   metathematiki[0]='\0';
    	   i=0;
    
    	   while ( (symbolo = (char) fgetc(fp))!= '\n')
    		{
    			metathematiki[i]=symbolo;
    			i++;
    			if (symbolo >= '0' && symbolo <= '9') //bre8hke oros
    			{
    				apotelesma = (float)(symbolo-'0');
    				othisi(&stoiva,apotelesma,&sfalma);
    			}
    			else if ( einai_telestis(symbolo) ) //bre8hke telesths
    			{
    				if (symbolo == '!')             // An einai paragontiko tote prepei na bgaloyme ena 
                    {                               // stoixeio apo ti stoiva
                       PopValue(stoiva,&oros1,&sfalma);
                       PopState(&stoiva,&sfalma);
                       apotelesma = (float) paragontiko((int)oros1);
    				   othisi(&stoiva,apotelesma,&sfalma);                                                  
                    }
    				else
                    {
                       PopValue(stoiva,&oros2,&sfalma);
                       PopState(&stoiva,&sfalma);
                       PopValue(stoiva,&oros1,&sfalma);
                       PopState(&stoiva,&sfalma);
                       apotelesma = upologismos(symbolo,oros1,oros2);
                       othisi(&stoiva,apotelesma,&sfalma);
                    }    
    			}
    		} // first while
    	 
         metathematiki[i]='\0';
         PopValue(stoiva,&apotelesma,&sfalma);
         PopState(&stoiva,&sfalma);
         printf("%s=%5.2f\n",metathematiki,apotelesma);
         } 	// second while
    
        fclose(fp);
        getchar();
        return 0;
    }

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Possibly it is crashing prior to that.

    There is a way to set VS to leave the console open so you don't have to use getchar(). Don't ask me what it is, but it would certainly be a better idea than all the "getchar()" nonsense people use at the end of their code. Can't you open a terminal into the compile directory, compile and run from there? It also makes much more sense to retain the output from each run, rather than having to open a new window each time, then closing it, etc.
    Last edited by MK27; 03-11-2010 at 08:50 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Meh, more code indented with a mix of spaces and tabs, resulting in an eyesore when posted.

    Code:
    int main(void)
    {
      int sfalma;
      typos_stoivas stoiva; //stoiva twn orwn
      float oros1,oros2,apotelesma;
      char symbolo, apantisi, metathematiki[256];
      int i;
    
      FILE *fp;
      
      if ( (fp=fopen("input.txt","r"))==NULL ) 
      {
        printf("Error opening file\n");
        exit(1);                                                                                          
      }  
      
      while (!feof(fp))	
      {	
        dimiourgia(&stoiva);
        metathematiki[0]='\0';
        i=0;
    
        while ( (symbolo = (char) fgetc(fp))!= '\n')
        {
          metathematiki[i]=symbolo;
          i++;
          if (symbolo >= '0' && symbolo <= '9') //bre8hke oros
          {
            apotelesma = (float)(symbolo-'0');
            othisi(&stoiva,apotelesma,&sfalma);
          }
          else if ( einai_telestis(symbolo) ) //bre8hke telesths
          {
            if (symbolo == '!')             // An einai paragontiko tote prepei na bgaloyme ena 
            {                               // stoixeio apo ti stoiva
              PopValue(stoiva,&oros1,&sfalma);
              PopState(&stoiva,&sfalma);
              apotelesma = (float) paragontiko((int)oros1);
              othisi(&stoiva,apotelesma,&sfalma);                                                  
            }
            else
            {
              PopValue(stoiva,&oros2,&sfalma);
              PopState(&stoiva,&sfalma);
              PopValue(stoiva,&oros1,&sfalma);
              PopState(&stoiva,&sfalma);
              apotelesma = upologismos(symbolo,oros1,oros2);
              othisi(&stoiva,apotelesma,&sfalma);
            }    
          }
        } // first while
        
        metathematiki[i]='\0';
        PopValue(stoiva,&apotelesma,&sfalma);
        PopState(&stoiva,&sfalma);
        printf("%s=%5.2f\n",metathematiki,apotelesma);
      } 	// second while
    
      fclose(fp);
      getchar();
      return 0;
    }
    > while (!feof(fp))
    This will NEVER be true, at the same time as this being false
    > while ( (symbolo = (char) fgetc(fp))!= '\n')

    feof() is a STATE (of a past event), not a prediction of a future action.
    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.

  4. #4
    Registered User
    Join Date
    Mar 2010
    Posts
    13
    The file I read in the program, consists of many lines ending in a newline character.

    My program works fine for all of these lines...I get the correct mathematical results for each line.

    Whenever I find a newline character, I make the calculations and then reenter the main while loop.

    The problem is that after reading the last line' s last character which is again a newline, the program should make the calculations and then find EOF. This could cause a close of file and a waiting for another carriage return from the keyboard.

    Do you think that my program fails to realize when this EOF comes?
    So, it never loops out?

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    The getchar() can be ignored or "skipped", if there is a newline in the keyboard buffer.

    add this line, just in front of your getchar line of code, for "industrial strength" holding the console text window, open:

    Code:
    while((ch = getchar()) != '\n');
    //your getchar() line goes here
    now, instead of getchar() just taking one char, it will take all the char's up to (and including), the first newline.

    Then your getchar() line should hold the console window open.

    If you have input numerous newlines at once, into your keyboard buffer, then you should remove them in a loop, of course.

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    As far as I can see, it will never exit.

    > while ( (symbolo = (char) fgetc(fp))!= '\n')
    If this loop exits, then feof() will be still be false, because there are no more reads from the file in between.

    > while ( (symbolo = (char) fgetc(fp))!= '\n')
    If this loop finds EOF, then it will loop forever; Having reached EOF, you've blown your chance of ever getting a \n to get you out of the loop.

    Personally, I would suggest this approach
    Code:
    // read a whole line
    while ( fgets( metathematiki, sizeof(metathematiki), fp ) != NULL ) {
      int i = 0;
      // examine each character on the line
      for ( i = 0 ; metathematiki[i] != '\0'; i++ ) {
        symbolo = metathematiki[i];
        // more stuff
      }
    }
    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.

  7. #7
    Registered User
    Join Date
    Mar 2010
    Posts
    13
    I wrote a simple program to check how I can get out of the loop and it works.
    However, I guess that there will be smarter ways to do this...

    Code:
    #include <stdio.h>
    
    int main(void) {
        
    FILE *fp;
    char ch;
    
         if ((fp=fopen("input.txt","r")) == NULL) {
            printf("The file cannot be opened\n");
            exit(1);
         } //end if
                
         while (!feof(fp)) {
    
            while ( (ch = getc(fp)) !='\n') {
               fputc(ch,stdout);           
            } //end while - checking the newline character
    
            fputc('\n',stdout);
            if ((ch=getc(fp))!=EOF) fputc(ch,stdout);
            else break;       
           
         } //end while - checking for end of file      
               
         getchar();
         fclose(fp);
         
         return 0;
        
    } //end main

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. c program help :>
    By n2134 in forum C Programming
    Replies: 9
    Last Post: 02-06-2010, 12:12 PM
  2. Using variables in system()
    By Afro in forum C Programming
    Replies: 8
    Last Post: 07-03-2007, 12:27 PM
  3. BOOKKEEPING PROGRAM, need help!
    By yabud in forum C Programming
    Replies: 3
    Last Post: 11-16-2006, 11:17 PM
  4. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM