1

I searched but didn't find a solution. The program is supposed to count tabs, newlines and spaces.

#include <stdio.h>

int main(void)
{
    int c,nl,tab,blank;
    tab = 0;
    blank = 0;
    nl = 0;

    while((c = getchar()) != EOF)
    {
        if(c == '\n');
            nl++;
        if(c == '\t');
            tab++;
        if(c == ' ');
            blank++;
    }

    printf("newline: %d tab: %d blank: %d\n", nl,tab,blank);

    return 0;
}

When I run this on FreeBSD using the ctrl-d to signal EOF, every variable is displayed with the same value. If I type "helloblank howtabareenteryouenterctrl-d" it displays newline as 18, tab as 18, blank as 18.

Is my code wrong? Obviously it is, but what's wrong?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

1

As the comment said, problem here is you have semicolons after your if statements. Generally, if statements are wrapped in braces as such:

    if(foo) {
        //your code here
    }

Try that and see if it works!

0

if (something); means literally: if something, then do nothing. the if statement syntax makes that putting the semicolon at the end converts it in a null statement to be executed if the condition something is true, so if the condition states, nothing is done. As you increment the three variables after the if statements, you'll have them incremented for each character you read from the file, and them all with the same value.

Solution

Just erase the ; after the condition right parenthesis, as in:

if(c == '\n') /* no semicolon here */
        nl++;

In a FreeBSD system:

$ make pru$$
cc -O -pipe  pru24720.c  -o pru24720
$ pru$$ <pru$$.c
newline: 23 tab: 0 blank: 123
Community
  • 1
  • 1
Luis Colorado
  • 10,974
  • 1
  • 16
  • 31
  • thanks, I have no idea what your make at the end does. I'm just starting with c so I guess ill work up to that. And I'm also beginning to learn unix so a lot of things are confusing but I learning a little a day. – clawhammer1234 May 26 '17 at 06:48
  • Well, when I answer a question here, I call always the file `pru$$.c`, which substitutes the `$$` by the pid of the shell, so it gets a different number (and fixed all the shell session). In this case, the shell pid was `24720`, so that was the name of the file... finally, I executed `pru24720` redirecting it's input from file `pru24720.c` (the source code) to get the number of lines of your sample code, number of tabs and number of blanks. – Luis Colorado May 26 '17 at 06:56
  • Is this a built in unix command or is it something you wrote? – clawhammer1234 May 26 '17 at 09:09
  • @clawhammer1234, `make(1)` is a standard unix command, and the shell substitution of the pid with `$$` is also standard of the bourne shell `sh(1)` and `bash(1)`. I have only written the `pru24720.c` to illustrate my answer, nothing else. – Luis Colorado May 28 '17 at 16:57