Hello,
I started learning C about 2 days ago, and now I have come to a problem that I can't figure out why I am getting the result I am getting. I bought a book, and I have proceeded quickly through it until now.
The problem I was given was this: "Write a program that reads input until encountering the # character and then reports the number of spaces read, the number of new line characters read, and the number of all other characters read."

Here is the source code I came up with:

#include <stdio.h>
#define SPACE ' '
int main(void)
{
    char c, prev;
    int space, newline;
    long other;
    
    space = 0;
    newline = 0;
    other = 0L;
    
    printf("Enter text to be analyzed (# to terminate):\n");
    
    while((c = getchar()) != '#')
    {
        if(c == (SPACE || '\n'))
        {
                if(c == SPACE)
                                space++;
                if(c == '\n')
                                newline++;
        }
        
    else
        other++;
        
    }
    
    printf("There are %d spaces, %d newline characters, and %d other characters.\n",
        space, newline, other);
        
    getchar();
    getchar();
    return 0;
}

Most everything works fine, except when I type Brent [ENTER] #, I get 6 other characters instead of just 5, one for each letter of Brent. I believe it might have something to do with the [ENTER] but I am not sure. Anyone have any ideas?

Looks like the code in my post didn't quite get formatted correctly when I copied my code over to the forum. Does anyone know how to simply copy what I have in my IDE, or do I have to do all the indentations again?

if(c == (SPACE || '\n'))
         {
                 if(c == SPACE)
                                 space++;
                 if(c == '\n')
                                 newline++;
         }
         else
         other++;
         }

The highligted code likely is not what you intend: it is a logical OR of ' ' with '\n' -- which results in true, a value of 1 (not the character '1', BTW). So you will only increment space or newline if c is equal to 1. Compare and contrast with this.

if ( c == SPACE )
 		 space++;
 	  else if ( c == '\n' )
 		 newline++;
 	  else
 		 other++;

Thank you very much. This helps a lot. It also shows me how to write more compact code, which I figure I will need when I start writing real software.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.