PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] Why I don't get the EOF?

 October 30, 2022     c, eof     No comments   

Issue

This is my code example. I wrote the question in my comment:

main(){
    long cnt; // chars count
    int c;

    /* Why the 'for' cicle doesn't finish when I input the
     * "a^Z" string and press ENTER? At this case '^Z' is
     * CTRL + Z (i.e this is EOF). I expected the second loop
     * will get the EOF (i.e. -1), but it has 26 instead of. Why?
     */
    for(cnt = 0; (c = getchar()) != EOF; ++cnt)
        ;

    printf("Chars count: %ld", cnt);
}

If I put a, ENTER, CTRL + Z, ENTER then I get the expected result: the CTRL + Z breaks the loop.

UPD

When I read info about getchar function then I saw that it uses the line-buffered input. It expects ENTER for pushing the data. I didn't see info that it also can push data when it get the Ctrl - Z. Therefore I expected that the second value will be EOF in my case (and the loop will be broken), i.e. I expectet that my string line will be parsed like the a, EOF, \n sequence.


Solution

When you press a+ CTRL + Z and then press ENTER, the CTRL + Z flushes the input (stdin) and the next input is \n, which is not an EOF. You need to press CTRL + Z twice to simulate the second EOF.



Answered By - Sourav Ghosh
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing