Thread: C programming Kernighan/ritchie example doesnt work properly

  1. #1
    Registered User
    Join Date
    Feb 2009

    C programming Kernighan/ritchie example doesnt work properly

    Hey guys,

    Ive been working through this book to learn C and when i compile one of the examples, the command window comes up, and i can type in it, but when i press enter, nothing happens, it just makes a new line, and the printf command in main() doesnt ever seem to execute. Please could anyone shine a light on why it may not be running properly? Any help would be greatly appreciated.


    // Read Line.cpp : Defines the entry point for the console application.
    #include <stdio.h>
    #define MAXLINE 1000 /* maximum input line size */
    int getline(char line[], int maxline);
    void copy(char to[], char from[]);
    /*print longest input line */
    	int len; /* current line legnth*/
    	int max; /* maximum length so far */
    	char line[MAXLINE]; /* current input line */
    	char longest[MAXLINE]; /* longest line saved here */
    	max = 0;
    	while ((len = getline(line, MAXLINE)) > 0)
    		if (len > max) {
    			max = len;
    			copy(longest, line);
    		if (max > 0) /* there was a line */
    			printf("%s", longest);
    		return 0;
    /* getline: read a line into s, return length */
    int getline(char s[], int lim)
    	int c, i;
    	for (i=0; i<lim-1 && (c=getchar())!= EOF && c!='\n'; ++i)
    		s[i] = c;
    	if (c == '\n') {
    		s[i] = c;
    	s[i] = '\0';
    	return i;
    /*copy: copy 'from' into 'to'; assume to is big enough */
    void copy(char to[], char from[])
    	int i;
    	i = 0;
    	while ((to[i] = from[i]) != '\0')

  2. #2
    ... kermit's Avatar
    Join Date
    Jan 2003
    != EOF
    The way the loops are set up, the longest line will not get printed out until the program sees EOF.

    Under Windows, you can do EOF with a ctrl-z key combo, and under Unix like systems, it is ctrl-d. Enter your text, and then do EOF, and you will see it works.
    Last edited by kermit; 09-08-2010 at 05:17 PM.

  3. #3
    Registered User
    Join Date
    Feb 2009
    thanks a lot for the reply, it works now, you've saved me a few headaches!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. MFC problem - getting buttons to work on tab dialogs
    By ThunderChicken in forum Windows Programming
    Replies: 3
    Last Post: 01-19-2010, 10:00 AM
  2. C++ system("rm") not deleting properly?
    By fattysmo in forum C++ Programming
    Replies: 4
    Last Post: 05-17-2008, 11:37 AM
  3. terminal output not showing output properly
    By stanlvw in forum C Programming
    Replies: 13
    Last Post: 11-19-2007, 10:46 PM
  4. help getting program to work
    By jlmac2001 in forum C Programming
    Replies: 2
    Last Post: 11-13-2002, 11:04 PM
  5. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM