Reputation: 21
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
Reputation: 59617
You're using the input
variable for two different things:
stdin
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
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
Reputation: 9962
Your input variable input
is also being used as the counter.
Upvotes: 3
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