Thread: Getchar terminating with new line or EOF

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    8

    Getchar terminating with new line or EOF

    Hi,

    I'm writing some code using the getchar function. The program should get the input character by character (using getchar) and ending when a new line character 'n' is reached or the EOF character is reached. Here's the code I worked out:

    Code:
    #include<stdio.h>
    
    int main(void)
    {
      char  c;
    
      printf("Please enter as many characters as you would like. Press enter or send
     the EOF character when you are done.\n");
    
      while( (c=getchar()) != EOF)
    
      return 0;
    }
    I know it's sloppy, but I'm a newbie so please bear with me. How can I fix this up so that I can read characters until a new line character 'n' is reached?

    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,659
    int c;
    while ( (c=getchar()) != EOF && c != '\n' )
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to do encryption in C
    By sankarv in forum C Programming
    Replies: 33
    Last Post: 12-28-2010, 11:01 AM
  2. Never find EOF after improperly formatted input
    By MALDATA in forum C Programming
    Replies: 5
    Last Post: 09-30-2008, 01:24 PM
  3. Could somebody please help me with this C program
    By brett73 in forum C Programming
    Replies: 6
    Last Post: 11-25-2004, 02:19 AM
  4. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM
  5. problem passing an option as command line argument
    By papous in forum C Programming
    Replies: 3
    Last Post: 11-22-2001, 06:12 PM