Sunday, October 30, 2022

[FIXED] How is EOF generated and interpreted in c based languages?

Issue

#include <stdio.h>

int main(){
    int c, nl=0;

    while((c = getchar()) != EOF)
        if(c=='\n')
            nl++;
                
    printf("%d",nl+1);
    return 0;
}

On Ubuntu 18.04, GCC 7.3.0

There's no output on console when the getchar() comparison is made with EOF. it works fine with other characters. Using CTRL^D exits the program with 'code 0' without any output on console. I've tried running it in bash but still no output.

input:

line 1

line 2

line 3

line 4

line 5

expected output:

5

actual output:

program exited with code 0


Solution

On *nix systems EOF is generated by Ctrl^D whereas on Windows system EOF is generated by Ctrl^Z. I am assuming that you are using Windows system. See https://en.wikipedia.org/wiki/End-of-file



Answered By - rootkea
Answer Checked By - Willingham (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.