Thread: feof and stdin

  1. #1
    Registered User
    Join Date
    Oct 2004
    Posts
    5

    feof and stdin

    Is this code OK?
    Code:
    ...
    char buf[BUFSIZ];
    	
    	while(1)
    	{
    		
    		
    		fgets(buf,BUFSIZ,stdin);
    		if(feof(stdin))
    			break;
    		printf("%s",buf);
    
    		
    	}
    ...
    I'm supposed to read one word at a time and process it in some way until user enters Ctrl-Z
    Is it ok to use feof(stdin)?
    And one more qustion; since fgets read newline character and store it in buffer do I have to loop to that position and set '\0' on that place, or is ti Ok '\n' to stay there because sometimes it can be annoying for example char name[100]; to have '\n' in the name
    Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    Yes, you can use feof() like that, but the code is a bit bulky

    You can do this to achieve the same effect
    Code:
    while ( fgets(buf,BUFSIZ,stdin) != NULL ) {
    	printf("%s",buf);
    }
    As for removing the newline, that is entirely up to you.
    The strchr() function is good for finding the newline, if you need to.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking stdin for input
    By hawaiian robots in forum C Programming
    Replies: 7
    Last Post: 05-19-2009, 09:06 AM