1

Im writing a simple program to count the number of character user is entered, and i wrote an if to check wether there is a newline but still printing it..

the code:

#include <stdio.h>

int main()

{
    char ch;
    int numberOfCharacters = 0;
    printf("please enter a word, and ctrl + d to see the resault\n");

    while ((ch = getchar()) != EOF)

    {
        if (numberOfCharacters != '\n')
        {
            numberOfCharacters++;
        }


    }

    printf("The number of characters is %d", numberOfCharacters);

    return 0;
}

what am i doing wrong?

JohnBigs
  • 2,691
  • 3
  • 31
  • 61
  • You may want to consider all control characters, not just new line. http://www.cplusplus.com/reference/cctype/iscntrl/ or conversely printable characters http://www.cplusplus.com/reference/cctype/isprint/ – Josh Petitt Jan 31 '13 at 20:34
  • 1
    Note that [`getchar()`](http://en.cppreference.com/w/c/io/getchar) returns an `int`, not a `char`. – hmjd Jan 31 '13 at 20:39
  • so ch should be int ch ? @hmjd – JohnBigs Jan 31 '13 at 20:56
  • 1
    @nir, yes. See http://stackoverflow.com/questions/7729339/getchar-inconsistency-with-variables/7729363#7729363 for why. – hmjd Jan 31 '13 at 21:06

2 Answers2

6

Think about this line:

    if (numberOfCharacters != '\n')

how can it make sense? You are comparing the number of characters read so far with a newline, it's like comparing apples to oranges and surely won't work. It's another variable that you should check...

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
  • 2
    Although your answer won't get selected, I like it because it smacks the OP upside the head & makes 'em think rather than just fixes the problem. – phonetagger Jan 31 '13 at 21:25
  • @phonetagger: thank you :); I think that's the kind of answer it's correct to give to one that is learning - he doesn't need ready made solutions, but hints to put him on the right way. – Matteo Italia Jan 31 '13 at 21:28
5

Change your loop to this.

while ((ch = getchar()) != EOF)
{
    if(ch != '\n') 
        numberOfCharacters++;
}
Achrome
  • 7,773
  • 14
  • 36
  • 45
  • Note that some platforms may require the pressing of ENTER in order to process the buffer. If you want single character input, you may have to use platform specific functions. – Thomas Matthews Jan 31 '13 at 23:46