[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]

Re: Re: File input problem



Ashwin forced the electrons to say:
> Hi,
> 
> >>   for( int j = 0; j < i; ++j )
> >
> >Make that j < i - 1 and you should be fine.
> 
> I checked.. (j < i) is right.

What do you mean, right?? j < i - 1 gives you the correct result,
doesn't it?

Here is your loop, quoted once again:

  while( inFile.good() )
  {
    s[i++] = inFile.get();
  }

If the input stream is the six characters, "linux\n", just check what
happens here. When i = 5, this reads the character \n from the stream,
setting i to 6. It has not hit EOF on the stream yet. So, infile.good()
will return true, and infile.get() is invoked again. This fetches you EOF,
and i is now _7_. In your next loop on j, i is 7.

If you are still not convinced, run the program through gdb once.

> >> <test.txt contents>
> >> linux
> >> <test.txt contains *only* five characters>
> >
> >six, my friend, there is a newline at the end.
> 
> I checked it with the HEX editor in KDE, this file had five 
> chars.

I don't know about the KDE hex editor, but any self respecting editor will
insert a newline at the end, unless you take pains to tell it not to do so.

Look at this typescript o/p:

Script started on Tue Nov 21 11:53:13 2000
binand@zaphod[~]:(1) cat test.txt
linux
binand@zaphod[~]:(2) wc test.txt
      1       1       6 test.txt
binand@zaphod[~]:(3) xxd < test.txt
0000000: 6c69 6e75 780a                           linux.
binand@zaphod[~]:(4) exit

Script done on Tue Nov 21 11:53:52 2000

See that 0x0a at the end? That is the newline. There are six characters,
unless you have specifically created the file without the newline (eg, via
echo -n "linux" > test.txt).

Binand

-- 
#define l/* Binand Raj S. <binand@xxxxxxxxxxxxxxxxxxxxx> */".%\"-\"("
#define s/* Ambition: To write sendmail.cf from scratch  */abs(abs(i)-5)
main(i,j){for(i=-5;i<6;i++){for(j=0;j<35-s;j++,putchar(32));putchar(s[l]^
108);for(j=0;j<2*s-1;j++,putchar(32));s&&putchar(s[l]^108);putchar(10);}}