Question

New to programming, working through K&R. After inputting using the stdin, I press ^D to write EOF (i'm using linux), and... nothing happens. I'm still able to write to the console, and able to ^Z to suspend, but not able to use ^D. I expected my code to read the input and print all the lines longer than the requirement, and as I can't produce any output, I'm not sure where to begin diagnosing my problem.

/*
Exercise 1-17 in K&R: page 31 in book
Write a program to print all input lines that are longer than 80 characters
*/

# include <stdio.h>
# define MIN_LINE 5         /*change to 80 for final*/
# define MAX_LINE 20        /*change for final*/

int getline(char line[], int max); 
void copy(char to[], char from[], int position);

int main()
{
    char line[MAX_LINE]; 
    int len = 0; 
    char print_register[MAX_LINE];
    int reg_index = 0;

    /*read length of line*/
    while ((len = getline(line, MAX_LINE)) != EOF)
    {
        /*if len > 80; append to print-array*/
        if (len > MIN_LINE) 
        {
            copy(print_register, line, reg_index); 
        }
    }

    /*print the print-array*/
    printf("%s", print_register); 

    return 0; 
}

int getline( char line[], int max)
{
    int i; 
    int c; 

    for (i = 0; (c = getchar()) != EOF && c != '\n' && i <= max; i++)
        {
            line[i] = c; 
        }
    /* handle '\n' and EOF */ 
    if (c == '\n')
    {
        line[i] = c; 
        i++; 
    }

    line[i] = '\0'; 

    return i;  
}

void copy(char to[], char from[], int position)
{
    int i;
    while ((to[position] = from[i]) != '\0')
    {
        i++;
        position++;
    } 
}
Was it helpful?

Solution 2

you need to initialize the "i" value in copy function, if not it may take some unexpected value and getline() output is returning number of characters not EOF so you need to change while loop condition also.

Changes:

Original : while ((len = getline(line, MAX_LINE)) != EOF)

changed : while ((len = getline(line, MAX_LINE)) != 0)

void copy(char to[], char from[], int position)
{
    // int i; Original
    int i =0;
    while ((to[position] = from[i]) != '\0')
    {
        i++;
        position++;
    } 
}

if you initialize i=0 in copy function, you will get output.

OTHER TIPS

Your getline() function returns the length and not EOF. Hence the following statement should be replaced:

while ((len = getline(line, MAX_LINE)) != EOF)

The EOF should be replaced with 0:

while ((len = getline(line, MAX_LINE)) != 0)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top