counting of characters in c programming language using getchar() to get input character

130 Views Asked by At
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
    
        int num=0,ch='9';
    
        while((ch=getchar())!=EOF){
            ++num;
        }
        printf("\n%d",num);
    }

/* this is a program to count no of characters entered using getchar(). 

suppose i entered

1
2
3
4
5

answer displayed is 10 not 5

*/enter image description here

1

There are 1 best solutions below

5
Vlad from Moscow On

The function getchar reads any character including white space characters as for example the new line character '\n' that corresponds to the pressed key Enter as demonstrated by the output of your program

If you want to skip white space characters you can write for example

#include <stdio.h>
#include <ctype.h>

int main( void )
{
    size_t num = 0;
    int ch;

    while ( ( ch = getchar() ) != EOF )
    {
        if ( !isspace( ch ) ) ++num;
    }

    printf( "\num = %zu\n", num );
}

If you want to skip only new line characters then the program can look the following way

#include <stdio.h>

int main( void )
{
    size_t num = 0;
    int ch;

    while ( ( ch = getchar() ) != EOF )
    {
        if ( ch != '\n' ) ++num;
    }

    printf( "\num = %zu\n", num );
}

An alternative approach is to use another standard function scanf as for example

#include <stdio.h>

int main( void )
{
    size_t num = 0;
    char ch;

    while ( scanf( " %c", &ch ) == 1 )
    {
        ++num;
    }

    printf( "\num = %zu\n", num );
}

Pay attention to the leading space in the format specification

scanf( " %c", &ch )
       ^^^

It allows to skip white space characters.