Thread: K&R Chap 5, getint() bug?

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    36

    K&R Chap 5, getint() bug?

    As a newbie it is hard to reconcile bugs in the K&R text vs simply things that I do not understand. Also, sometimes the requirements for the sample programs are a little bit vague as to what exactly they are supposed to do.

    However, both of those things said, I have been staring at getint() on page 87 for well over an hour, and running tests, and I am fairly certain there is a pretty large bug:

    Code:
    int getch(void);
    void ungetch(int);
    
    /* getint: get next integer from input into *pn */
    int getint(int *pn)
    {
    	int c, sign;
    	while (isspace(c = getch())) /* skip white space */
    		;
    	if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
    		ungetch(c); /* it is not a number */
    		return 0;
    	}
    	sign = (c == '-') ? -1 : 1;
    	if (c == '+' || c == '-')
    		c = getch();
    	for (*pn = 0; isdigit(c), c = getch())
    		*pn = 10 * *pn + (c - '0');
    	*pn *= sign;
    	if (c != EOF)
    		ungetch(c);
    	return c;
    }
    What happens here is if the character being "got" is not a number, it pushes it back to the input and returns zero. Then when the function is called again... it gets that same character, and does the same thing again. Forever. So it never gets past that character to the rest of the input.

    I just want a sanity check from a more experienced C programmer to verify that my reasoning above is correct. Thanks!

  2. #2
    Registered User
    Join Date
    Aug 2011
    Posts
    385
    I've been having problems with this book too. Things are a little complicated. your program is on page 97 by the way....

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    The idea is probably that you don't call getint() again right away. It likely stopped scanning due to finding '+', '-', or end-of-line. You'd have to check for these operators and condition before calling getint() the next time.

  4. #4
    Registered User
    Join Date
    May 2011
    Posts
    36
    Quote Originally Posted by nonoob View Post
    The idea is probably that you don't call getint() again right away. It likely stopped scanning due to finding '+', '-', or end-of-line. You'd have to check for these operators and condition before calling getint() the next time.
    Oh, so I guess you're saying another function would be clearing the ungetch() buffer?

    That makes sense, I guess... but yeah it is very unclear how this function is intended to be used... or what sort of non-digit characters are expected to be encountered in the input.

    Everyone says K&R is like THE book to learn C, but I am not quite seeing that so clearly. My first language was Java, and I used the Headfirst book... and the whole process was very painless and every single step made perfect sense (partially because I think Java is easier to understand, and partially because the book I used was awesome). I wish there was a book written that well for C. Any ideas? I'll probably finish K&R anyway (am actually on my second go through now), but it could never hurt to have another one.

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by The111 View Post
    Oh, so I guess you're saying another function would be clearing the ungetch() buffer?

    That makes sense, I guess... but yeah it is very unclear how this function is intended to be used... or what sort of non-digit characters are expected to be encountered in the input.

    Everyone says K&R is like THE book to learn C, but I am not quite seeing that so clearly. My first language was Java, and I used the Headfirst book... and the whole process was very painless and every single step made perfect sense (partially because I think Java is easier to understand, and partially because the book I used was awesome). I wish there was a book written that well for C. Any ideas? I'll probably finish K&R anyway (am actually on my second go through now), but it could never hurt to have another one.
    You might like "Teach Yourself C in 21 days"... I used it and found it very easy to digest.

    Also... just a little nudge to the wise here... It would be a terrible mistake to try to compare C to Java. First they are two completely different languages, written for entirely different programming mindsets. Second Java does a lot of behind the scenes "babysitting" that C does not. And, finally, trying to learn something new in the context of something old will *always* disappoint you.

    You should probably approach C as something totally new, go through K&R, start on page 1, read every word, type up and compile all the examples and exercises, then play with the code until you understand it... then turn the page.

    Edit: Out of curiosity, what OS and compiler are you working with?
    Last edited by CommonTater; 12-02-2011 at 01:21 PM.

  6. #6
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by juice View Post
    I've been having problems with this book too. Things are a little complicated. your program is on page 97 by the way....
    It is a very in-depth look at C... So, yes it's going to be complex. But then, programming isn't exactly easy to begin with.

  7. #7
    Registered User
    Join Date
    May 2011
    Posts
    36
    Quote Originally Posted by CommonTater View Post
    You might like "Teach Yourself C in 21 days"... I used it and found it very easy to digest.

    Also... just a little nudge to the wise here... It would be a terrible mistake to try to compare C to Java. First they are two completely different languages, written for entirely different programming mindsets. Second Java does a lot of behind the scenes "babysitting" that C does not. And, finally, trying to learn something new in the context of something old will *always* disappoint you.

    You should probably approach C as something totally new, go through K&R, start on page 1, read every word, type up and compile all the examples and exercises, then play with the code until you understand it... then turn the page.

    Edit: Out of curiosity, what OS and compiler are you working with?
    Sorry if I wasn't clear, but my intent was not to compare C with Java, it was to compare two different learning tools. I am getting along pretty with the syntax and other rules as presented in the K&R text, but as I stated earlier the requirements of the examples in the text are very unclear. For example, the one in question here (getint), is explained by the text to:

    "perform free-format input conversion by breaking a stream of characters into integer values, one integer per call."

    That is all that is said, so if I take it at face value and assume I have an input stream like this

    1 2 3 z 5 6 7

    It fails, because it gets stuck with z in the ungetch() buffer forever. A reply above suggested that other functions may be intended to work on the ungetch() buffer before getint() is called again, which is believable, but so are 100 other things. To a total newbie, examples are what make the concepts easy to understand, and many (but certainly not all) of the examples in the K&R text only make sense if you make a bunch of assumptions. If you make the wrong assumptions, you can still make the code work, but you have to change it... for example by removing the one ungetch() line I highlighted in red in my OP, I can make the input stream above work. And in the end, all that effort DID help me understand C better... but through no merit of the text.

    The exercises are often unclear too, but that is sort of ok because in that case, starting from a blank slate, it is more reasonable to make assumptions and end up with your own interpretation of what is required. But with the example codes AS GIVEN, it should be more clear what they are intended for. For the one above... a sample input/output might have cleared up the confusion.

    But thanks for the recommendation on the other text. I may digest that one after I finish my 2nd go through K&R.

  8. #8
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Keep in mind that Kernahan and Richie are not high school teachers. They operate at a level somewhere above "How do I turn this on?" when it comes to computers. Some of the examples may not make much sense to you *right now* but they will in time.

    For example... the unget and return in that function serve to protect data from loss... the function returns on a non-digit value so that whatever is being input is not lost. It is up to you to detect the error, clean up and carry on. The alternative is that a character string might be lost or scrambled ...

    Consider an input stream like this... 43 zombies 12 mushrooms 13 elephants and 1 tuba

    Remember it did say "free form" input... so when your getInt() function hits the z in zombies it has to put the z back or lose it resulting in a call to getString() that returns "ombies" which would cause errors.

    If you are simply seeking a bunch of ints and don't care about the strings... your job, when the function returns an error, is to clean up the stream to find the next int and then call the function again.

    The function does behave correctly...

  9. #9
    Registered User
    Join Date
    May 2011
    Posts
    36
    Quote Originally Posted by CommonTater View Post
    your job, when the function returns an error, is to clean up the stream to find the next int and then call the function again.
    That makes perfect sense, but it seems slightly at odds with what the text says.

    The text says that getint() will break a stream into integers. It doesn't say that getint() will need another function to help it get to the next int in the stream, if it encounters an alphabet letter. Admittedly, nor does it say that getint() won't need help (hence the ambiguity). But to me the implication is that getint() will handle the entire stream. Admittedly I could be overlooking some sort of standard assumption made my more experienced programmers... but to me it is hardly obvious.

    Thanks for the example though, it does seem like one logical interpretation of how the getint() function could be used...

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by The111 View Post
    That makes perfect sense, but it seems slightly at odds with what the text says.

    The text says that getint() will break a stream into integers. It doesn't say that getint() will need another function to help it get to the next int in the stream, if it encounters an alphabet letter. Admittedly, nor does it say that getint() won't need help (hence the ambiguity). But to me the implication is that getint() will handle the entire stream. Admittedly I could be overlooking some sort of standard assumption made my more experienced programmers... but to me it is hardly obvious.

    Thanks for the example though, it does seem like one logical interpretation of how the getint() function could be used...
    No worries...

    As I say these guys operate on a slightly higher plain than a raw beginner... That's why I suggested 21 days as a "catch up" piece to get you started off nice and easy. Mind you, like all textbooks about complex technical issues ... it's going to have it's problems too. Just hopefully not the same ones

    I programmed for nearly 10 years in Pascal before switching to C in 2004, so I came to the language with a background at a similar level (both function based languages, no OOP). The first couple of months studying C were largely punctuated with "WTF???" said loudly and in full words over and over again... Your experience brings you from a different mindset altogether so I can certainly understand how some things may seem a little mysterious and frustrating to you...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strange effect of braces (K&R chap 1)
    By montka in forum C Programming
    Replies: 5
    Last Post: 06-26-2011, 09:32 AM
  2. Question in getint #2
    By jongmin in forum C Programming
    Replies: 5
    Last Post: 03-10-2004, 01:10 AM
  3. question in getint
    By jongmin in forum C Programming
    Replies: 2
    Last Post: 03-09-2004, 01:27 AM
  4. getint()
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 05-23-2002, 06:18 PM