Thread: problem with getchar()

  1. #1
    Registered User blob84's Avatar
    Join Date
    Jun 2010
    Posts
    46

    problem with getchar()

    Hi, i have a problem using getchar:
    Code:
    #include <stdio.h>
    
    int main () {
    	int c;
    	char a = 'a';
    	while ( (c = getchar()) != a ) {
    		printf("hello");
    	}
    }
    It prints "hello" twice, because i think it sees the '\n' character.
    ??

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    So:

    if(c != '\n')

    needs to be inserted above the printf() statement, doesn't it?

  3. #3
    Registered User
    Join Date
    Aug 2010
    Posts
    63
    when you execute your program, a prompt will invite you to enter some charachers and the program will calculate the number of char you have entred until you enter the char 'a' and he will dispaly 'N' * hello times, with N = the number of char you entred.

    So you can see 'a' in your program as a terminating char of the execution.

    Regards.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  2. getchar() problem
    By jlharrison in forum C Programming
    Replies: 6
    Last Post: 01-25-2006, 02:49 PM
  3. problem with parser code
    By ssharish2005 in forum C Programming
    Replies: 2
    Last Post: 12-02-2005, 07:38 AM
  4. Replies: 5
    Last Post: 11-07-2005, 11:34 PM