0

I'm trying to find out the number of tabs, spaces and newlines in my C program. The code is :

#include <stdio.h>

void main()
{
    char c;
    int tabs=0 , spaces=0 , nl=0 ;
    printf("Provide the input");
    scanf("%c" , &c);
    while(c != EOF)
    {
        if(c == ' ')
        spaces++;
        else if(c == '\n')
        nl++;
        else if(c == '\t')
        tabs++;
        scanf("%c" , &c);
    }
    printf("blanks:%d\nspaces:%d\nnewlines:%d" , spaces , tabs , nl);
}

Well, I'm expecting it to do just that but the code is just not moving beyond accepting the input phase. What am I doing wrong? Below is what my command line looks like:

[tejas@localhost The_C_Programming_Language]$ cc Exercise_1-8.c

[tejas@localhost The_C_Programming_Language]$ ./a.out

Provide the input seguiofgawie

gweuigwh

e u w   f qw[uwf            
[PHWUO FEFF 
qah fuwpfyh fweor

(I keep pressing the Return key but to no end. Please help. Thank you for reading. This is my first question, hope i didn't do anything wrong...)

EDIT: getchar() doesn't work either, and I'm currently using Fedora 26 and GEDIT as my text editor

EDIT: getchar() works, in order to send the EOF character, one should press Ctrl+D on an empty line and if you want it done in with just one press of the RETURN key, change your loop condition to variable != '\n'. I apologize for spreading misinformation.

Melebius
  • 5,590
  • 3
  • 34
  • 46

2 Answers2

2

There is a small error here that you are commiting, by comparing the scanned char value to EOF. Quoting another answer

EOF is a macro which expands to an integer constant expression with type int and an implementation dependent negative value but is very commonly -1.

However, since you are reading from stdin, you won't be able to enter it as a single char since it will be considered as 2 characters and will not produce the desired result. In a nutshell, your program is behaving in the desired way. In order for it to exit input mode, just change your while condition to something which you are able to meet.

funny_geek
  • 41
  • 6
0

i think, a character given by the user cannot be compared to EOF(end of file) as you are not dealing with any file i.e., you have not opened any file in order to verify its end.

yogeswaran
  • 11
  • 2