0

I read input with the following loop

do
{
      i=0;
      do
      {
          line[i]=fgetc(stdin);
          i++;

      }while(i<100 && line[i-1]!='\n' && line[i-1]!=EOF);

      //Parsing input

 }while(line[i-1]!=EOF);

My input looks like this

$GPRMC,123519,A,4510.000,N,01410.000,E,010.0,010.0,120113,003.1,W*4B
$GPRMC,123520,A,4520.000,N,01650.000,E,010.0,010.0,230394,003.1,W*4B
$GPRMC,123521,A,4700.000,N,01530.000,E,010.0,010.0,230394,003.1,W*4F
$GPRMB,A,0.66,L,001,002,4800.24,N,01630.00,E,002.3,052.5,001.0,V*1D
$GPGGA,123523,5000.000,N,01630.000,E,1,08,0.9,100.0,M,46.9,M,,*68

So my problem is that after the last line, when it should read EOF, it stops on the line line[i]=fgetc(stdin);. Even if I copy that input from file and paste it to terminal or even if I run that program with < input.txt in terminal.But when I run it in terminal, paste there input and than manually add EOF (^D) than it stops.. Can someone tell me where I get problem?

3 Answers3

0

replace do-while with just while and try. The condition will be checked after you have found EOF, i mean, even after EOF, you are doing the fgetc(stdin) which is incorrect

Aadishri
  • 1,341
  • 2
  • 18
  • 26
0
#include <stdio.h>

int main(int argc, char *argv[]){
    char line[100+1];
    int ch;

    do{
        int i=0;
        while(EOF!=(ch=fgetc(stdin)) && ch !='\n' && i<100){
            line[i++]=ch;
        }
        line[i]='\0';
        if(*line){
            //Parsing input
            printf("<%s>\n", line);
        }
    }while(ch != EOF);

    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
0

You are reading up to 100 characters into char line[]. You terminate with either 100 characters read in or '\n', or EOF; This is the specification of fgets().

So consider using one call fgets(), which matches your code logic. With fgets, amounts to this:

while(fgets(line, 100, stdin)!=NULL )  // get up to \n or 100 chars, NULL return means usually EOF
{
   char *p=strchr(line, '\n');
   if(p!=NULL) *p=0x0;

   // parsing input
}
// here you should also check for NULL caused by system errors and not EOF -- maybe using feof(stdin)
jim mcnamara
  • 16,005
  • 2
  • 34
  • 51
  • your code stops on the `while(fgets(line, 100, stdin)!=NULL` line, when it gets to the end of file, with < inpu.txt in terminal –  Apr 18 '13 at 13:16