Uddhava Swaminathan
Uddhava Swaminathan

Reputation: 31

Line Counter In C

I am reading a book called C Programming Language 2nd Edition. There it teaches a program called character counting. But according to the output it does not.It just takes the character and does nothing. This is the first version:

#include <stdio.h>
#include <stdlib.h>

main() {
    int c, nl;

    nl = 0;
    while ((c = getchar()) != EOF)
        if (c == '/n')
            ++nl;
    printf("%d\n", nl);
}

So when i type my sentence and press Ctrl+Z to satisfy EOF it gives me zero:

I am a good person
CTRL+Z
0

Press any key to return

It is supposed to count lines and being a beginner I could not understand.

Upvotes: 1

Views: 1308

Answers (4)

No Idea For Name
No Idea For Name

Reputation: 11597

might be that the program want to know if the next char is not an end of a line ( '\n') so you'll need:

#include <stdio.h>
#include <stdlib.h>

main() {
    int c, nl;

    nl = 0;
    while ((c = getchar()) != EOF)
        if (c != '\n')
            ++nl;
    printf("%d\n", nl);
}

this will count the number of characters, but there are others escape characters such as '\t' and so i'm not quite sure what the program is supposed to do, but i think that in your book you'll find some more description clarifying that part

for counting the number of lines simply change '/n' to '\n' as you probably know by now

Upvotes: 0

Evil Dog Pie
Evil Dog Pie

Reputation: 2320

It looks as if you're missing a set of {} brackets:

#include <stdio.h>
#include <stdlib.h>

main()
{
    int c, nl;

    nl = 0;
    while((c = getchar()) != EOF)
    {   // <- This starts the block to be repeated
        if (c == '\n')
        {   // <- This is just to keep the code 'safe' ...
            ++nl;
        }   // <- ... as is this
    }   // <- This ends the block to be repeated
    printf("The number of New Line characters entered was %d\n", nl);
}

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234865

Although the immediate problem is a simple case of replacing '/n' with '\n' (i.e. escaping n for the newline character which is what the backslash does), the fact that your code compiles and runs is due to the C99 standard:

6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined."

'/n' is a character array consisting of the forward slash and the letter n.

Once you've fixed that, you then will need to make changes to count characters as opposed to just newline characters.

Upvotes: 3

Codor
Codor

Reputation: 17605

Apparently the implementation is supposed to count only the number of newline characters, not the number of total characters, as implemented in the if(c=='\n') condition. The program returns 0 on your input as it does not contain a newline character.

Upvotes: 2

Related Questions