473,602 Members | 2,774 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

K&r chapter-1; exc-17


Q. Write a program to print all input lines that are longer than 80
characters.

Code taken from
http://users.powernet.co.uk/eton/kandr2/krx117.html

=============== =========code== =============== ==========
#include <stdio.h>
#define MINLENGTH 81

int readbuff(char *buffer) {
size_t i=0;
int c;
while (i < MINLENGTH) {
c = getchar();
if (c == EOF) return -1;
if (c == '\n') return 0;
buffer[i++] = c;
}
return 1;
}

int copyline(char *buffer) {
size_t i;
int c;
int status = 1;
for(i=0; i<MINLENGTH; i++)
putchar(buffer[i]);
while(status == 1) {
c = getchar();
if (c == EOF)
status = -1;
else if (c == '\n')
status = 0;
else
putchar(c);
}
putchar('\n');
return status;
}

int main(void) {
char buffer[MINLENGTH];
int status = 0;
while (status != -1) {
status = readbuff(buffer );
if (status == 1)
status = copyline(buffer );
}
return 0;
}
=============== =============== ==code========= ===========
My doubts are:

1)Why there are two getchar functions in copyline and readbuff. Can it
be done with one
global buffer pointer?

2) status variable in the main function is either 1 ,0,-1. I have seen
codes uses this kind of checking a function’s return type. That is
initializing the variable at first either with 0 or 1 and then checking
the modified value of that variable with function return type. Does this
practice carry any name?
--
"Combinatio n is the heart of chess"
A.Alekhine
Mail to:
sathyashrayan AT gmail DOT com
(AT = @ and DOT = .)
Nov 14 '05 #1
35 1798

"sathya" <sa****@nomail. com> wrote in message
news:41******** *******@nomail. com...

Q. Write a program to print all input lines that are longer than 80
characters.

Code taken from
http://users.powernet.co.uk/eton/kandr2/krx117.html

=============== =========code== =============== ==========
#include <stdio.h>
#define MINLENGTH 81

int readbuff(char *buffer) {
size_t i=0;
int c;
while (i < MINLENGTH) {
c = getchar();
if (c == EOF) return -1;
if (c == '\n') return 0;
buffer[i++] = c;
}
return 1;
}

int copyline(char *buffer) {
size_t i;
int c;
int status = 1;
for(i=0; i<MINLENGTH; i++)
putchar(buffer[i]);
while(status == 1) {
c = getchar();
if (c == EOF)
status = -1;
else if (c == '\n')
status = 0;
else
putchar(c);
}
putchar('\n');
return status;
}

int main(void) {
char buffer[MINLENGTH];
int status = 0;
while (status != -1) {
status = readbuff(buffer );
if (status == 1)
status = copyline(buffer );
}
return 0;
}
=============== =============== ==code========= ===========
My doubts are:

1)Why there are two getchar functions in copyline and readbuff. Can it
be done with one
global buffer pointer?

2) status variable in the main function is either 1 ,0,-1. I have seen
codes uses this kind of checking a function's return type. That is
initializing the variable at first either with 0 or 1 and then checking
the modified value of that variable with function return type. Does this
practice carry any name?


Although K&R has somehow gotten away from me in the holiday shuffle, I think
this code ignores the development of the text. In particular, the
instructions are to WRITE the program in question, as opposed to poaching
it. That aside, your questions are topical but beyond my ability to answer
with any degree of veracity. MPJ
Nov 14 '05 #2
sathya wrote:
Q. Write a program to print all input lines that are longer than 80
characters.

Code taken from
http://users.powernet.co.uk/eton/kandr2/krx117.html

=============== =========code== =============== ==========
#include <stdio.h>
#define MINLENGTH 81

int readbuff(char *buffer) {
size_t i=0;
int c;
while (i < MINLENGTH) {
c = getchar();
if (c == EOF) return -1;
if (c == '\n') return 0;
buffer[i++] = c;
}
return 1;
}

int copyline(char *buffer) {
size_t i;
int c;
int status = 1;
for(i=0; i<MINLENGTH; i++)
putchar(buffer[i]);
while(status == 1) {
c = getchar();
if (c == EOF)
status = -1;
else if (c == '\n')
status = 0;
else
putchar(c);
}
putchar('\n');
return status;
}

int main(void) {
char buffer[MINLENGTH];
int status = 0;
while (status != -1) {
status = readbuff(buffer );
if (status == 1)
status = copyline(buffer );
}
return 0;
}
=============== =============== ==code========= ===========
My doubts are:

1)Why there are two getchar functions in copyline and readbuff.
If you take code from someone else and do not understand it:
Try it out!
If we have a line with >80 characters, the getchar() calls in readbuff()
were used to fill buf with the first 80 characters.
In copyline(), we write the contents of buf in one go and then print
out all the excess characters up to the end of the line or until
we encounter EOF.
We cannot read more than 80 characters into buf as buf is large enough.
On the other hand, if we wanted to output all characters in one go
with a getchar()/putchar() combination, we would have to "go back"
80 characters at realizing that we have more than 80 as we have just
"used up" these 80.
Can it
be done with one
global buffer pointer?
I am not sure what you mean by that. If you want to declare buf
on file scope and not pass buf to either readbuf() or copyline(),
that is a Bad Idea. Read your C book or this group's FAQ to
find out why.
Once more: Try it out!
If you have an idea, try it. Then, you can come back and show us.

2) status variable in the main function is either 1 ,0,-1. I have seen
codes uses this kind of checking a function’s return type. That is
initializing the variable at first either with 0 or 1 and then checking
the modified value of that variable with function return type. Does this
practice carry any name?


status can be initialized with anything but -1 for the program
to work.
You could take any three values to do it. Moreover, you can
#define ENCOUNTERED_EOF -1
#define GEQ_MINLENGTH 1
use them instead of -1/1, redefine them to have any values and
so on. Instead of 0, you can return _anything_ but ENCOUNTERED_EOF
and GEQ_MINLENGTH.
<0, ==0, >0 are often used to signal whether something compared
less than, equal to, greater than something else.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #3
Merrill & Michele wrote:

[snip: Topical question to a program not written by the OP]


Although K&R has somehow gotten away from me in the holiday shuffle, I think
this code ignores the development of the text. In particular, the
instructions are to WRITE the program in question, as opposed to poaching
it. That aside, your questions are topical but beyond my ability to answer
with any degree of veracity. MPJ


While you are right on the reminder that the OP would do better
to write the program himself, the last sentence exposes that you
are not going to either answer it (or part of it) or pose a topical
question related to his request -- and that you are aware of it.
This is bad practice. If your "bad practice" posts exceed a certain
threshold in relation to your topical posts, you will end up in many
more killfiles.
If you cannot contain your urge to spill out words, feel free to do
so where this is welcome. There are many newsgroups. Come here only
for C.
-Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #4
In <30************ *@uni-berlin.de> Michael Mair <Mi**********@i nvalid.invalid> writes:
If you take code from someone else and do not understand it:
Try it out!


This is horrible advice. The code may be horribly broken, but still
working by pure accident. If the newbie sees that it works, he's likely
to assume that it is correct C code and try to learn from it.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Currently looking for a job in the European Union
Nov 14 '05 #5

Dan Pop wrote:
In <30************ *@uni-berlin.de> Michael Mair <Mi**********@i nvalid.invalid> writes:
If you take code from someone else and do not understand it:
Try it out!


This is horrible advice. The code may be horribly broken, but still
working by pure accident. If the newbie sees that it works, he's likely
to assume that it is correct C code and try to learn from it.


You are right -- unqualified and without context this is horrible
advice. (Too many perl books lately...)

What I meant was: The code is advertised to be working and solving
the problem. The OP obviously believed that and from that assumption,
I went forward. Find out what happens by trying out modifications of
the parts you believe to understand and work your way down.
In this case, I would have tried modifying the output routine to
see what is going on...
IMO, writting it yourself and afterwards looking at "how it also
can be done" is much better -- you recognize the advantages and
disadvantages of both approaches and can fix bugs which escaped
the original author (or you yourself). If this is not an option, you
have to do the second best.
For badly commented complex source which I do not understand from
just reading around, I do about the same: Go to a safe box, run
with the debugger through it to get a feeling what happens
structurally, change the input data and the replacable parts.
Then, I have an image in my mind where what is going and can
figure out the relevant parts and the operations.
For long-term solutions, building the structure and the special
stuff from scratch (using libraries for the parts which really
need not be reinvented) is often better.

BTW: People who just get source from the web and want to learn
the language from that are at least naive. If I want to learn
something, I look for the community, their FAQ and the books they
recommend; even though it is not always given, there are often
good books in electronic form for free.
If there is nothing for free, I still can try a library. If then
still nothing can be turned up, then one can sigh and go by the
good old "informatio n is power -- and power is expensive"... :-/
-Michael
--
E-Mail: Mine is a gmx dot de address.

Nov 14 '05 #6
"Michael Mair"
Merrill & Michele wrote:


[snip: Topical question to a program not written by the OP]


Although K&R has somehow gotten away from me in the holiday shuffle, I think this code ignores the development of the text. In particular, the
instructions are to WRITE the program in question, as opposed to poaching it. That aside, your questions are topical but beyond my ability to answer with any degree of veracity. MPJ


While you are right on the reminder that the OP would do better
to write the program himself, the last sentence exposes that you
are not going to either answer it (or part of it) or pose a topical
question related to his request -- and that you are aware of it.
This is bad practice. If your "bad practice" posts exceed a certain
threshold in relation to your topical posts, you will end up in many
more killfiles.
If you cannot contain your urge to spill out words, feel free to do
so where this is welcome. There are many newsgroups. Come here only
for C.


Michael, I would love to have posted MY version of 1-17, but I can't find
anything around this dump. If, after one more hour of tearing this place
apart to find K&R, I get a negative return value, I'll go get a new one. As
for killfiles, I know more than most about killing, less than most about
files and have no idea what the marriage of the two notions means. MPJ
Nov 14 '05 #7
Merrill & Michele <be********@com cast.net> wrote:
...As
for killfiles, I know more than most about killing, less than most about
files and have no idea what the marriage of the two notions means. MPJ


http://www.dickalba.demon.co.uk/usen.../faq_kill.html

--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #8
"Michael Mair
Dan Pop wrote:
If you take code from someone else and do not understand it:
Try it out!
This is horrible advice. The code may be horribly broken, but still
working by pure accident. If the newbie sees that it works, he's likely
to assume that it is correct C code and try to learn from it.


You are right -- unqualified and without context this is horrible
advice. (Too many perl books lately...)

[snipped]
BTW: People who just get source from the web and want to learn
the language from that are at least naive. If I want to learn
something, I look for the community, their FAQ and the books they
recommend; even though it is not always given, there are often
good books in electronic form for free.
If there is nothing for free, I still can try a library. If then
still nothing can be turned up, then one can sigh and go by the
good old "informatio n is power -- and power is expensive"... :-/


Changing the topic slightly, but I think to do so in the direction of the
OP.
The following is lifted heavily from K&R §1.9, but with the bracing and
spacing style that I think is best. The substantive change is that I've
used char *foo instead of char foo[]. I thought Sosman called the
difference akin to coconuts vs mangoes. Anyways, the darn thing doesn't
compile, the first complaint coming from the int getline... that comes right
after main(). ++thanks MPJ

#include <stdio.h>
#define MAXLINE 5000

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

int main(void){

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);
}
}

/*to console */
if (max > 0) printf("%s\nlen gth was%d \n", longest, max);

return 0;

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;
++ i;
}
s[i] = '\0';

return i;
}

void copy(char *to, char *from) {

int i;

i = 0;
while ((to[i] = from[i]) != '\0') ++ i;
}
Nov 14 '05 #9
Merrill & Michele <be********@com cast.net> wrote:
The following is lifted heavily from K&R §1.9, but with the bracing and
spacing style that I think is best. The substantive change is that I've
used char *foo instead of char foo[]. I thought Sosman called the
difference akin to coconuts vs mangoes.
They do differ, but in the context of calling a function (or to be
precise, treating an array in value context) coconut can look rather
similar to a mango.
Anyways, the darn thing doesn't
compile, the first complaint coming from the int getline... that comes right
after main(). ++thanks MPJ #include <stdio.h>
#define MAXLINE 5000 int getline(char *line, int maxline);
void copy(char *to, char *from); int main(void){ 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);
}
} /*to console */
if (max > 0) printf("%s\nlen gth was%d \n", longest, max); return 0;
You're missing a closing brace '}' here for main(). If you start using
some more reasonable indentation it will get easier to spot such
problems (probably you should try to find an editor that indents
new lines when you hit <TAB> or some other key - then you see
immediately on what block level you are).
int getline(char *s, int lim) { int c, i; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++ i;) s[i]
= c;
There's a semicolon at the end of the for loop condition that's not
supposed to be there. The compiler should tell you that.
if (c == '\n' {
You're missing a ')' for the if condition. Again the compiler will
tell you.
s[i] = c;
++ i;
You can write that in a single line. i.e.

s[ i++ ] = c;
}
s[i] = '\0'; return i;
} void copy(char *to, char *from) { int i; i = 0;
while ((to[i] = from[i]) != '\0') ++ i;
}


If you get further in K&R you will find that the whole function can
be written as

void copy( char *to, const char *from )
{
while ( *to = *from )
;
}

or the whole thing simplified using the standard function strcpy( ) ;-)

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

192
8860
by: Kwan Ting | last post by:
The_Sage, I see you've gotten yourself a twin asking for program in comp.lang.c++ . http://groups.google.co.uk/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&th=45cd1b289c71c33c&rnum=1 If you the oh so mighty programmer that you pretend to be, why don't you just write some? (And oh, void main is still not allow by the C++ standard.) Seeming as how you tried to quote the standard in an attempt to pretend you're right, I'll quote the standard to once...
5
8670
by: Jukka K. Korpela | last post by:
The HTML specifications define the entities &zwj;, &zwnj;, &lrm;, &rlm; as denoting zero-width joiner, zero-width non-joiner, left to right mark, and right to left mark. Is there any evidence of any browser support to the characters so denoted, in the sense defined in the Unicode standard, chapter 15? ( &zwj;, &zwnj;, &lrm;, &rlm; ) For example, does f&zwj;i ever produce an fi ligature? In my tests, the best I get is that the characters...
0
1090
by: Ben Jacobs-Swearingen | last post by:
Hello, I just started learning C a couple weeks ago from Kernighan and Ritchie (first edition -- I can't afford the newer second edition), and have really enjoyed it so far. But I am having trouble making the code at the end of Chapter 5 -- the sort function that uses function pointers -- to work on my machine (233 Mhz iMac, 160 MB RAM, OS 9.2 ; MPW environment). When I try to compile sort.c with the Symantec C compiler it gives me all...
27
3362
by: Ben Jacobs-Swearingen | last post by:
Hello, I just started learning C a couple weeks ago from Kernighan and Ritchie (first edition -- I can't afford the newer second edition), and have really enjoyed it so far. But I am having trouble making the code at the end of Chapter 5 -- the sort function that uses function pointers -- to work on my machine (233 Mhz iMac, 160 MB RAM, OS 9.2 ; MPW environment). When I try to compile sort.c with the Symantec C compiler it gives me all...
6
4129
by: Herrcho | last post by:
in K&R Chapter 6.3 it mentions two methods to calculate NKEYS. and points out the first one which is to terminate the list of initializers with a null pointer, then loop along keytab until the end is found is less efficient than using sizeof operator , since size of the array is completely determined at compile time. i don't quite understand this. Could anyone explain to me in detail ?
10
2596
by: Eric | last post by:
Hello, I have been working through the K&R book (only chapter one so far) examples and exercises. After much sweat and hair pulling, I think I have a solution for ex 1-18 on page 31. It seems to work but may be missing some error checking. Can you please take a look and see if my logic is correct and any other improvements. This is not a homework but it could just as well be. I am trying to get a
0
5546
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted ******************************************************** For this teeny job, please refer to: http://feeds.reddit.com/feed/8fu/?o=25
9
3025
by: JFS | last post by:
I know most of you have probably read "The C Programming Language" (K&R) at some point. Well here is something that is driving me crazy. The exercises are impossible (most of them) for me to do. I am not even done with the first chapter and I am already ripping out my hair trying to get the exercises completed. It is driving me crazy and making me very very angry. Here is an example of what I am talking about: Chapter 1.6 Arrays...
26
2098
by: rajiv.battula | last post by:
Hey everyone, I am a Java programmer, somewhere between novice to advanced. I wanted to know if it is still recommended to read "The C Programming Language" 2nd Edition? This edition was released in 1988, it is now 2007, almost 20 years. Also, since it is so old, is there some supplemental tutorial recommend to go along with it? Thanks for your advice. Rajiv Battula
0
7993
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8404
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8268
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6730
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5440
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3944
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2418
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1510
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1254
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.