MDrake
MDrake

Reputation: 39

Having trouble counting lines in output

Here is the code :

#include <stdio.h>

int main(void) {
    int nextChar;
    int numLines = 0;

    while  ((nextChar = getchar())!= EOF) {
        if (nextChar == '\n') {
           ++numLines;
        }
    }
    printf("The\nsky\nis\nblue\n");
    printf("%d lines read.\n", numLines);
    return 0;
}

It runs, but returns 0 lines read. I've tried putting the 'the sky is blue' text in a bunch of different places, but nothing seems to work.

The code was shown in the book, but without

    printf("The\nsky\is\blue.\n");

but the output was shown as:

    The
    sky
    is
    blue.
    4 lines read.

any suggestions??

Upvotes: 3

Views: 87

Answers (2)

brianxautumn
brianxautumn

Reputation: 1162

Okay I think I see what you are trying to do. First you have to decide exactly how you are getting your input. I'll just assume for now you would like to get it from the command line. When you were using getChar(), its counting 1 character plus the new line, so you were actually just counting how many characters you typed in. When you get a line from the console, its counting \ as one char and n as another char. What you can do is manually detect your escape characters within the string, because it seems that you are interested in detecting the sequence "\n". Every time you hit enter and it returns the line from the console you will actually get the '\n' character at the end, which is different than "\n", you can count that separately if you like. Here is an example to illustrate:

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

int main(void) {
    char* currentChar;
    char* nextChar;
    int numLines = 0;
    int bufferSize = 100;
    char *input;
    int inputLength;

    input = (char *) malloc(bufferSize);
    inputLength = getline(&input, &bufferSize, stdin);

    for (int i = 0; i < inputLength; i++) {
        currentChar = input[i];
        if (currentChar == '\\' && i < inputLength - 1) {
            nextChar = input[i + 1];
            if (nextChar == 'n')
                numLines++;
        }
    }

    printf("%d lines read.\n", numLines);
    return 0;
}

Upvotes: 0

abhiarora
abhiarora

Reputation: 10430

Your program is looking for EOF to break out from while loop. To enter an EOF, use:

^Z (Ctrl + Z) in Windows
^D on Unix-like systems

CTRL + D works for me on Ubuntu. I have run your code in my machine. To get your desired output, you need to type -

The  (Press Enter) 
Sky  (Press Enter)
is   (Press Enter) 
Blue (Press Enter) 
(and finally send EOF)

Pressing ENTER will send '\n' character to the program on Ubuntu. Windows uses \r\n to signify the enter key was pressed, while Linux and Unix use \n to signify that the enter key was pressed.

Upvotes: 2

Related Questions