Solved

Display number of characters

Posted on 2000-05-11
14
213 Views
Last Modified: 2010-04-15
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
Comment
Question by:pyramid
  • 4
  • 4
  • 3
  • +3
14 Comments
 
LVL 3

Expert Comment

by:sburck
ID: 2800347
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
 
LVL 4

Expert Comment

by:captainkirk
ID: 2800682
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
 
LVL 1

Author Comment

by:pyramid
ID: 2801584
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
 
LVL 4

Expert Comment

by:captainkirk
ID: 2801662
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
 
LVL 1

Author Comment

by:pyramid
ID: 2801975
No..not going to work..

I don't have that header file...
and argv argc are never used in the program..
0
 
LVL 4

Expert Comment

by:captainkirk
ID: 2802153
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
 
LVL 4

Expert Comment

by:wylliker
ID: 2802194
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 2

Expert Comment

by:serg111
ID: 2802584
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
 
LVL 1

Author Comment

by:pyramid
ID: 2804379
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
 
LVL 4

Expert Comment

by:wylliker
ID: 2804692
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
 

Expert Comment

by:haren
ID: 2806212
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
 
LVL 4

Expert Comment

by:wylliker
ID: 2807260
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
 
LVL 1

Author Comment

by:pyramid
ID: 2816989
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
 
LVL 4

Accepted Solution

by:
wylliker earned 50 total points
ID: 2818095
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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now