Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie question 1

Status
Not open for further replies.

Zabbala

Programmer
Feb 8, 2004
1
US
Hi, Im new to C and this is my first post here so please bear with me.
I have a little problem: I have this little program that prints the longest line, but I don't know how to provide input to it:

#include <stdio.h>
#define MAXLINE 1000

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

main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];

max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0)
printf(&quot;%s&quot;, longest);
}
return 0;
}
int getline(char s[], int lim)
{
int c, i;
for (i=0; i<lim -1 && (c=getchar()) !=EOF && c!='\n'; ++i)
s = c;
if (c == '\n') {
s = c;
++i;
}
s = '\0';
return i;
}

void copy(char to[], char from[])
{
int i;
i = 0;
while ((to = from) != '\0')
++i;
}
Your help would be very appreciated.
 
You're using the function getchar to get your input; it reads from standard input. That means you should be able to start this program from a command prompt then type the lines directly into it.

To indicate that you're finished typing lines, you'd give it an end-of-input character, which is typically Ctrl-D on UNIX-like systems, Ctrl-Z on DOS/Windows, and I have no idea on Mac.
 
First of all, let's see if I understand your requirement corretly: you want your program to accept many lines of inputs and then print out the longest line. --if this is true, then you need to make a minor change:

change
while ((len = getline(line, MAXLINE)) > 0)
to
while ((len = getline(line, MAXLINE)) > 1)

and finish input by pressing &quot;Enter&quot; without any proceeding character while executing your program.

Your problem is: you don't have a way to stop the &quot;while&quot; loop, it will loop forever with &quot;0&quot;! but with &quot;1&quot;, length of &quot;Enter&quot; (first '\n' then converted to '\0'), which is &quot;1&quot;, indicates the end of input and exits the loop.

Besdies, you should run debug and watch the varialbes to find the problem and try to write clear comments as a good programming habbit.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top