• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 258
  • Last Modified:

Display number of characters

Hi,

I wrote this program that is suppose to read in file from disk, display the contents and count the characters. I read in successfully, display the contents but I am have problem getting
the right character count.

The file contains the alphabet in lower case written in a DOS editor.

Any solutions

thanks in advance

P....

/* Program test2.c                 */

/* INCLUDE AND PREPROCESSOR STATEMENTS */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/* BEGIN MAIN PROGRAM */

main()
{
FILE *fp;
long count[26];
/* OPEN FILE FOR READING */
int in_char;

if ( (fp=fopen("alpha.txt", "r")) == NULL)
   {
   fprintf(stderr, "Error Reading File");
   exit(1);
   }

/* WHILE NOT END OF FILE, READ AND DISPLAY */
in_char = fgetc(fp);

while ( in_char != EOF )
  {
  putchar(in_char);
  in_char = fgetc(fp);
  count[in_char]++;
  }

printf("There are %d characters in the file", count[in_char]);
fclose(fp);
return (0);
}
0
pyramid
Asked:
pyramid
  • 4
  • 4
  • 3
  • +3
1 Solution
 
sburckCommented:
Looking at your code, I'm not sure I understand what you want.  If you want the total number of characters in the file, then count shouldn't be an array, it should just be a long, and the code should look:

long count = 0;

....
count++;

....
printf("There are %d characters in the file",count);

If you want to count how many of each type of character, then you need an array, with room for all characters, not just 'A'..'Z', and that would be

long count[256].

The increment you have is then fine, but you need to loop on your printf to say

for(i=0;i<256;i++)
    printf("There are %d characters of ASCII value %d in the file\n", count, i);
0
 
captainkirkCommented:
Agreed - your code would look more like this:

/* Program test2.c                 */

/* INCLUDE AND PREPROCESSOR STATEMENTS */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


/* BEGIN MAIN PROGRAM */

main()
{
FILE *fp;
long count;
/* OPEN FILE FOR READING */
int in_char;

if ( (fp=fopen("alpha.txt", "r")) == NULL)
   {
   fprintf(stderr, "Error Reading File");
   exit(1);
   }

/* WHILE NOT END OF FILE, READ AND DISPLAY */
in_char = fgetc(fp);

while ( in_char != EOF )
  {
  putchar(in_char);
  in_char = fgetc(fp);
  count++;
  }

printf("There are %d characters in the file", count);
fclose(fp);
return (0);
}
0
 
pyramidAuthor Commented:
Thanks for your reply. Here is the output I am looking for..

First, the file contents

abcdefghijklmnopqrstuvwxyz

Second,

"You have 26 characters in the file "

I run the code from captainkirk I get the following;

abcdefghijklmnopqrstuvwxyz

and..

"You have 67 characters in the file"

Damn it Jim! I'm a doctor, not a programmer! ;-)(Couldn't resist)
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
captainkirkCommented:
Here's the program with count initialized to zero (and my own stylistic preferences):

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
     FILE *fp;
     long count = 0;

     int in_char;

     if ((fp = fopen("d:\\alpha.txt", "r")) == NULL)
     {
          fprintf(stderr, "Error Reading File");
        exit(1);
     } // end if

     in_char = fgetc(fp);

     while (in_char != EOF)
     {
          putchar(in_char);
        in_char = fgetc(fp);
        count++;
     } // end while

     printf("There are %d characters in the file", count);
     fclose(fp);
     return 0;
} // end main()

This code is tested and prints out the correct count: 26...


0
 
pyramidAuthor Commented:
No..not going to work..

I don't have that header file...
and argv argc are never used in the program..
0
 
captainkirkCommented:
take out the #include "stdafx.h" if you need to, and set the settings for the .cpp file to not use precompiled headers. It does not matter whether or not argv and argc are used...
0
 
wyllikerCommented:
There must be something wrong with your file.  Have you checked it's size on disk - because this should be the same size as what you are printing out.

That is unless you are required to ignore all whitespace (spaces, carriage returns, line feeds, tabs, etc) and you have been given a file with them in it.

One other thing ... This code

while ( in_char != EOF )
  {
  putchar(in_char);
  in_char = fgetc(fp);
  count[in_char]++;
  }

.... would be better written as

while (!feof(fp))
  {
  count++;
  putchar(in_char);
  in_char = fgetc(fp);
  }

That all said, it looks as though from reading your code that you were trying to get a count of each of the characters by having an array of longs (long count[26]).

The problem you face is that when you do ...

  count[in_char]++;

in_char IS NOT between 0-26. in_char will be the values 97-122.

What you would need to do to count each of the characters is like this ...


At the top ...

long count[32];
long Total = 0;

   memset(count, 0, sizeof(count));


In your while loop for counting ...

while (!feof(fp))
  {
  Total++;
  count[in_char & 0x001F]++;
  putchar(in_char);
  in_char = fgetc(fp);
  }


This line would adjust in_char to be in the range of 0 through 31 (you would only be interested in the counts stored in array positions 1 through 26).

  count[in_char & 0x001F]++;


Total - would be the count of all characters


If you needed the total count of just the lower case alphabet then you would need to do ...

At the top ...
int ii = 0;


After your while loop for counting ...

for(ii = 1; ii < 27; ++ii)
   Total += count[ii];


0
 
serg111Commented:
When you write

long count[26];

your count[26] is not initialized, and count[i] at that point could have any value.

Add following code at beginning:

for(i=0;i<26;i++)
 count[i]=0;
0
 
pyramidAuthor Commented:
Thanks for your proposed answer serg111
but wylliker's comment has the information I needed to get closest to the result I want for now. I think the points should go to wyllikers.

p...
0
 
wyllikerCommented:
I am still concerned about the original code you had posted that reported 67 characters.

Have you checked the file?  Are there whitespace characters you have to ignore?

You have to do a little more here, if so.  To ignore whitespace characters you would have to change your counting loop to have ...


  if(!iswhitespace(in_char))
     count[in_char & 0x001F]++;


If this is not an issues you can leave this part out.
0
 
harenCommented:
Hi try to run following program !

/* Program test2.c                 */
/* INCLUDE AND PREPROCESSOR STATEMENTS */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* BEGIN MAIN PROGRAM */
main()
{
 FILE *fp;
 long count;
 /* OPEN FILE FOR READING */
 int in_char;

 if ( (fp=fopen("alpha.txt", "r")) == NULL)
   {
    fprintf(stderr, "Error Reading File");
    exit(1);
   }

/* WHILE NOT END OF FILE, READ AND DISPLAY */
/*initialize the count to zero*/
count = 0;
in_char = fgetc(fp);
while ( in_char != EOF )
  {
  putchar(in_char);
  /* increment the count if there is an alphabet. for tabs and spaces it will not increment */
  if(isalpha(in_char))
       count++;
  in_char = fgetc(fp);
  }

printf("There are %d characters in the file", count);
fclose(fp);
return (0);
}


good luck...

0
 
wyllikerCommented:
Actually for whitespace to be removed it would be ...

 if(!isspace(in_char))
      count[in-char & 0x001F]++;


Sorry about that.  Had the word whitespace stuck in my head.
0
 
pyramidAuthor Commented:
No need to be concerned wyliker. I have solved the rest of my problem when you pointed me in the right direction.

Basically, I used the location of count++ you put in your code to count all the characters in the file. Then I limited the characters displayed to the screen by using a conditional that looks only for characters that match the alphabet in the ascii table and voila, a count of 26 characters.

Not bad for C rookie,I think.

If you would present you question in the form of an answer, the points are yours.

P..
0
 
wyllikerCommented:
I will submit my comment as an answer.

FYI ...
You can just accept a comment as an answer.

This is generally preferred as it allows experts to participate without locking the question.

Answer starts here
--------------------------------


There must be something wrong with your file.  Have you checked it's size on disk - because this should be the same size as what you are printing out.

That is unless you are required to ignore all whitespace (spaces, carriage returns, line feeds, tabs, etc) and you have been given a file with them in it.

One other thing ... This code

while ( in_char != EOF )
  {
  putchar(in_char);
  in_char = fgetc(fp);
  count[in_char]++;
  }

..... would be better written as

while (!feof(fp))
  {
  count++;
  putchar(in_char);
  in_char = fgetc(fp);
  }

That all said, it looks as though from reading your code that you were trying to get a count of each of the characters by having an array of longs (long count[26]).

The problem you face is that when you do ...

  count[in_char]++;

in_char IS NOT between 0-26. in_char will be the values 97-122.

What you would need to do to count each of the characters is like this ...


At the top ...

long count[32];
long Total = 0;

   memset(count, 0, sizeof(count));


In your while loop for counting ...

while (!feof(fp))
  {
  Total++;
  count[in_char & 0x001F]++;
  putchar(in_char);
  in_char = fgetc(fp);
  }


This line would adjust in_char to be in the range of 0 through 31 (you would only be interested in the counts stored in array positions 1 through 26).

  count[in_char & 0x001F]++;


Total - would be the count of all characters


If you needed the total count of just the lower case alphabet then you would need to do ...

At the top ...
int ii = 0;


After your while loop for counting ...

for(ii = 1; ii < 27; ++ii)
   Total += count[ii];



To ignore whitespace characters you would have to change your counting loop to have ...


if(!isspace(in_char))
      count[in-char & 0x001F]++;



0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 4
  • 3
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now