-3

I wanted to know how text is formatted while reading to and writing from a file. So I tried the following code on a g++ compiler. Also, I am using the < bits/stdc++.h > library.

while(!feof(fptr)) {                      //fptr is the pointer to the input file
    int i = fgetc(fptr);
    printf("%c - %d\n",i,i);
}

The input file contains the following text.

spaces 
and newlines

The output I got was this.

s - 115
p - 112
a - 97
c - 99
e - 101
s - 115
  - 32

 - 10
a - 97
n - 110
d - 100
  - 32
n - 110
e - 101
w - 119
l - 108
i - 105
n - 110
e - 101
s - 115
� - -1

I understand the last line was because of the EOF, which wasn't a character.

But why is there an empty line in the output?

shards
  • 21
  • 2
  • Are you using C or C++? This looks like C code. – NathanOliver Apr 09 '18 at 16:56
  • 1
    An [ASCII table](http://en.cppreference.com/w/c/language/ascii) might be useful as a reference. And think about you ***input!*** – Some programmer dude Apr 09 '18 at 16:57
  • 2
    Also please read [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Some programmer dude Apr 09 '18 at 16:58
  • 1
    You may want to read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) . – Jesper Juhl Apr 09 '18 at 16:59
  • When you printed the character which represented a new line at the end of the first line of text, what did you expect to see? A new line! – Gem Taylor Apr 09 '18 at 17:47

1 Answers1

2

Why is there an empty line in the output

Add delimiters to format line as follows to help you understand what is going on:

int i;
while((i = fgetc(fptr)) != EOF) {
    printf("'%c' - %d\n",i,i);
}//         ^  ^

Now the last line with -1 will be gone because we check for EOF before entering loop's body; this is better than calling feof (why?).

The "empty line" will change as follows:

' ' - 32
'
' - 10

With delimiters in place it is easy to see that 32 corresponds to a space, while 10 corresponds to line feed.

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399