Problem displaying characters

This is a discussion on Problem displaying characters within the C Programming forums, part of the General Programming Boards category; I was trying to write a program that counts each occurrence of a character in a given array of characters... ...

  1. #1
    Registered User
    Join Date
    Jan 2005
    Posts
    204

    Problem displaying characters

    I was trying to write a program that counts each occurrence of a character in a given array of characters...
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    int main(void)
    {
    	int c;
    	int counter[256 + 1] = {0};
    
    	printf("Type your name followed by #: ");
    	while((c = getchar()) != '#')
    	{
    		if(c == ' ' || c == '\n' || c == '\t')
    			continue;
    
    		++counter[tolower(c)];
    	}
    
    	for(c = 0; c < 256; c++) {
    		if(counter[c] > 0)
    			printf("%c = %d\n", counter[c], counter[c]);
    	}
    
    	printf("\n");
    
    	return 0;
    }
    It seems to be counting the characters correctly but take a look at what it displays when I type, let's say, Max Payne:
    Type your name followed by #: Max Payne#
    ☻ = 2
    ☺ = 1
    ☺ = 1
    ☺ = 1
    ☺ = 1
    ☺ = 1
    ☺ = 1

    Can someone help me fix this? Thanks.

  2. #2
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,220
    Code:
    #include <stdio.h>
    #include <ctype.h>
    
    int main(void)
    {
    	int c;
    	int counter[256 + 1] = {0};
    
    	printf("Type your name followed by #: ");
    	while((c = getchar()) != '#')
    	{
    		if(c == ' ' || c == '\n' || c == '\t')
    			continue;
    
    		++counter[tolower(c)];
    	}
    
    	for(c = 0; c < 256; c++) {
    		if(counter[c] > 0)
    			printf("%c = %d\n", c, counter[c]);
    	}
    
    	printf("\n");
    
    	return 0;
    }

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    204

    I have to pay more attention! Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with reading characters
    By csvraju in forum C Programming
    Replies: 4
    Last Post: 03-31-2009, 07:59 AM
  2. A peculiar problem in displaying a file.
    By cheemais in forum C Programming
    Replies: 22
    Last Post: 10-03-2007, 10:25 AM
  3. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 02:51 PM
  4. Problem writing ASCII characters in file
    By sho1 in forum C++ Programming
    Replies: 5
    Last Post: 10-12-2006, 01:51 PM
  5. Problem with array in displaying a string
    By Makoy in forum C++ Programming
    Replies: 2
    Last Post: 10-17-2004, 04:45 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21