Cagrosso
Cagrosso

Reputation: 195

Counting Spaces in input and getting a massive number of them

I'm going through the C Programming Language 2nd Edition and am stuck on Exercise 1-8. I get the correct output for the number of newlines and the number of tabs, but I get an incorrect number of spaces.

# include <stdio.h>

main() {
    /* we use long as the int bit storage is rather limited */
    long blanks, tabs, newlines;
    /* c is an int as we are checking it against the ASCII values */
    int c;

    printf("Enter text: ");
    while ((c = getchar()) != EOF) {
        if (c == ' ') {
            blanks++;
        }
        if (c == '\t') {
            tabs++;
        }
        if (c == '\n') {
           newlines++;
        }
    }
    printf("Spaces = %d\nTabs = %d\nNewlines = %d\n", blanks, tabs, newlines);
}

Using this as input (note that I am using \t and \n to show where I am pressing tab and return to make it obvious):

hello there c\t
\n
\n
\n

Gets me the output:

Spaces = 1408281626
Tabs = 1
Newlines = 3

Is there a reason I am getting such a massive number of spaces? I have looked at other answers and my answer seems sound, I thought that maybe it might have something to do with the terminal I am using. I am using a Macbook on El Capitan, could that have something to do with it?

Upvotes: 0

Views: 55

Answers (2)

tdao
tdao

Reputation: 17668

Two issues:

  • Always initialize your variables.
  • Use correct format for printf. You are using long so %ld instead of %d.

So,

long blanks = 0, tabs = 0, newlines = 0;

and,

printf("Spaces = %ld\nTabs = %ld\nNewlines = %ld\n", blanks, tabs, newlines);

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

You did not initialize the following variables

long blanks, tabs, newlines;

Write instead

long blanks = 0, tabs = 0, newlines = 0;

Also use format specifier %ld in this call of printf

printf("Spaces = %ld\nTabs = %ld\nNewlines = %ld\n", blanks, tabs, newlines);

Take into account that according to the C Stnadard function main without parameters shall be declared like

int main( void )

Upvotes: 2

Related Questions