Reputation: 85
I'm continue working with the Classic K&R Book "The C Programming Language", Second Edition.
I was having problems with the output of exercise in page 22 about word counting. Not getting the desired output.
Finally I think that found a mistake in the code syntax ?
Exercise say (Copy and paste from PDF):
1.5.4 Word Counting The fourth in our series of useful programs counts lines, words, and characters, with the loose definition that a word is any sequence of characters that does not contain a blank, tab or newline. This is a bare-bones version of the UNIX program wc.
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c = '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw;
}
}
printf("%d %d %d\n", nl, nw, nc);
}
Where Say:
if (c == ' ' || c == '\n' || c = '\t')
No need to say?
if (c == ' ' || c == '\n' || c == '\t')
Please.
If my assessment is correct. The same error appears later on page 23 which explains the line.
It tells me exactly what the logic but it seems so incredible that this error is in a book like this. I need a confirmation, there will be this freaking.
Thank soo much in advance for your comments.
What's difference in 2 lines? Make question more clear. – Rohan 33 mins ago.
Hello and Thanks to question. In C
x = 5 is used to assign to the variable x the value 5, for example.
However, if what you want is to check the equality symbol is correct ==
if x == 5 Say if x is equal to 5 ...
As you can see the book are assigning c = '\t'
which makes no sense and was giving me errors
"If c is equal to tab" is if (c == '\t')
Where \t are the TAB key.
I hope I have clarified some doubt
And thanks for asking
You can check http://www.tutorialspoint.com/cprogramming/c_operators.htm
Where you can see:
== Checks if the values of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.
Upvotes: 1
Views: 726
Reputation: 13854
Yes, you are correct in your assessment that the =
needs to be replaced with a ==
.
Typos happen, even in books and even in K&R.
However, you mention that you copied the code straight from a PDF. That PDF was likely OCRed from a book and OCR software is far from perfect, so mistakes can do happen.
Upvotes: 1