I'm trying to learn C, or re-learn as the case may be. I've been stuck for a long time on something simple from Chapter 1 in the Kernighan and Ritchie C book. There is an example to read lines of text, then output the longest line entered.
The problem is that the Mac Terminal does not seem to send NULL or empty string when you don't type anything, and just hit return. So, the program will not stop until you hit control-C. I also tried the getline function from later in the book, but it doesn't solve the problem. Any help would be appreciated!
Here's the code:
The problem is that the Mac Terminal does not seem to send NULL or empty string when you don't type anything, and just hit return. So, the program will not stop until you hit control-C. I also tried the getline function from later in the book, but it doesn't solve the problem. Any help would be appreciated!
Here's the code:
Code:
#include <stdio.h>
#include <string.h>
#define MAXLINE 1000 /*maximum input line size*/
int getlineKR(char [], int);
int getline2KR(char [], int);
void copyKR(char [], char []);
/*
print longest input line
from Kernighan and Ritchie, 2nd edition, pg 29
Changes made to allow for use of getline on pg 165
KR or 2KR added to function names
*/
int main (int argc, char * argv[]) {
int len; /* current line length */
int max; /* maximum line length */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
printf("Enter a line of text:\n");
max = 0;
while ((len = getlineKR(line, MAXLINE)) > 0)
/* while ((len = getline2KR(line, MAXLINE)) > 0) */
if (len > max) {
max = len;
copyKR(longest, line);
}
if (max > 0) /* there was a line */
printf("%s", longest);
return 0;
}
/* getline: read a line from standard input into s, return length
from Kernighan and Ritchie, 2nd edition, pg 29 */
int getlineKR(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;
++i;
}
s[i] = '\0';
return i;
}
/* getline: read a line from standard input into s, return length
from Kernighan and Ritchie, 2nd edition, pg 165 */
int getline2KR(char *line, int max) {
if (fgets(line, max, stdin) == NULL)
return 0;
else
return strlen(line);
}
/* copy: copy 'from' into 'to'; assume to is big enough
from Kernighan and Ritchie, 2nd edition, pg 29 */
void copyKR(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '\0')
++i;
}