Nikki Orlando
Nikki Orlando

Reputation: 21

Counting a series of characters in C

All it's supposed to do is count the characters a user enters, and print it out. Can't use arrays, and must be terminated by the user. I have no idea what's wrong with this. Any tips?

#include <stdio.h>

int main( int argc, char *argv[] )
{
  int input;

  printf( "Enter a series of characters:\n" );

  input  = getchar( );

  while ( input != EOF )
    {
    input++;
    input = getchar( );
    }

  printf( "You entered %d characters.\n", input );

  return 0;

}

Upvotes: 1

Views: 120

Answers (4)

pb2q
pb2q

Reputation: 59617

You're using the input variable for two different things:

  • to get the next character from stdin
  • and to count the total number of characters entered.

The first usage messes up the second: using input to store the next character, you overwrite the character count.

You need 2 different variables for the two different purposes.

int input;
int characterCount = 0;

// your loop:
    characterCount++;
    input = getchar( );

Upvotes: 2

Adrian Cornish
Adrian Cornish

Reputation: 23868

Comments inline

#include <stdio.h>

int main( int argc, char *argv[] )
{
  int input;

  printf( "Enter a series of characters:\n" );

  input  = getchar( );

  while ( input != EOF )
    {
/* Good so far - you have read a char from the user */
    input++;
/* Why are you increment the user entered char by 1 - you need a separate counter */
    input = getchar( );
/* Now you read another char from the user (to be mangled on next loop iteration */
    }

  printf( "You entered %d characters.\n", input );

  return 0;

}

Upvotes: 1

Joseph Quinsey
Joseph Quinsey

Reputation: 9962

Your input variable input is also being used as the counter.

Upvotes: 3

Jerry Coffin
Jerry Coffin

Reputation: 490128

Did you intend input to hold the current input, or the number of characters you've read? You currently seem to be trying to use it for both, but it can only hold one or the other.

Upvotes: 4

Related Questions