简体   繁体   中英

Finding the number of times a character appears in a standard input text

For a project, I am trying to take an input from the keyboard, and create a table that shows the number of times that certain characters that appear. Here are the instructions:

"Read characters from standard input until EOF (the end-of-file mark) is read. Do not prompt the user to enter text - just read data as soon as the program starts. Keep a running count of each different character encountered in the input, and keep count of the total number of characters input (excluding EOF).

Note there are a total of 128 ASCII codes, equal to the value of the symbolic constant NUM defined in common.h. Get familiar with the features of common.h - many of them are handy, and you will be required to use some of them in later steps.

Print a neat table that shows each different input code, the corresponding character and its count, and print the total count at the end. Do not print any rows for ASCII codes that are not included in the input text.

You must exactly match the format of our solution's basic results, and so you must use the symbols and functions defined in common.h. Do NOT print anything any other way.

Use prHeader one time at the start.

Use prCountStr for each row that corresponds to a special character (codes 0-32, and 127), and use the symbol strings provided in common.h.

Use prCountChr for each row that corresponds to a printable character (codes 33-126).

Use prTotal one time at the end.

You can test it by typing text manually, in which case you must enter ctrl-D on Linux (or ctrl-Z on Windows) to end the input. Or better, test it by redirecting a file using the Linux redirection operator ('<'). For example, to input this sample text file named sample.txt, in our second sample run, notice that we typed the following: "

Here is the code that I have so far:

int main(int argc, char *argv[])
{
    int i=0,i2=0, totalCount=0;
    char character, counter[10000]={0};
    int shownArray[NUM]={0};
    FILE *out;
    out = fopen(OUTPUT, "w");
    prHeader(out);

    if (out == NULL)
    {
        printf("ERROR opening files. \n");
        return 1;
    }
    else
    {
        printf("SUCCESS opening files. \n");
        while (scanf("%c", &character) != EOF)
        {
            counter[totalCount++] = character;
            printf("%c", character);
        }

        for(i=0; i<NUM;i++)
        {
            for(i2=0;i2<=totalCount;i2++)
            {
                if(shownArray[i] == (int)counter[i2])
                    shownArray[i]++;
            }
        }

        for(i=0; i<NUM; i++)
        {

            if(shownArray[i]>0)
            {
                if(i <= 32)
                {
                    prCountStr(out,i,symbols[i],shownArray[i]);
                }
                else if(i == 127)
                {
                    prCountStr(out,i,symbolDel,shownArray[i]);
                }
                else
                {
                    char c=i;
                    prCountChr(out, i,c, shownArray[i]);
                }
            }
        }
        prTotal(out,totalCount);
    }
    fclose(out);
    return 0;
}

This is common.h

/*
   common.h - include at start of counts.c for

   Use the constants, symbols, macros and functions herein to
   insure that your printed results accurately match our
   solution's results. Do not print by any other means.

   Do not change this file, and especially do not rely on any
   changes to it. You will not turn this file in.
*/

#ifndef COMMON_H
#define COMMON_H
#include <stdlib.h>

/* constants: number of different characters, and
              first and last printable characters */
#define NUM 128
#define FIRST '!'
#define LAST '~'

/* symbols for special characters, corresponding to codes 0 through FIRST-1 */
char *symbols[] = {"NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK",
    "BEL", "BS", "HT", "LF", "VT", "FF", "CR", "SO", "SI", "DLE", "DC1",
    "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC",
    "FS", "GS", "RS", "US", "SPC" };

/* symbol for DEL character, code LAST+1 (same as NUM-1) */
char *symbolDel = "DEL";

/* the following four functions must be used to print results */

/* use prHeader at the start to print header row (titles) */
void prHeader(FILE *out) {
    fprintf(out, "Code\tChar\tCount\n----\t----\t-----\n");
}

/* use prCountStr to print count for one of the special symbols */
void prCountStr(FILE *out, int code, char *str, int count) {
    fprintf(out, "%3d\t%s\t%5d\n", code, str, count);
}

/* use prCountChr to print count for one of the printable characters */
void prCountChr(FILE *out, int code, char chr, int count) {
    fprintf(out, "%3d\t%c\t%5d\n", code, chr, count);
}

/* use prTotal at the end to print total character count */
void prTotal(FILE *out, int count) {
    fprintf(out, "\t\t-----\nTotal\t\t%5d\n", count);
}

/* use the following three macros to print error messages for part 2
   {
       Beware: each macro executes two statements.
   }
   ignore these macros for part 1 */

/* use BADFILE(name) to exit if a file (name) cannot be opened */
#define BADFILE(name) fprintf(stderr, "bad file: %s\n", (name)); \
                      exit(1);

/* use BADOPTION(op) if an invalid option (not '-o') is on command line */
#define BADOPTION(op) fprintf(stderr, "bad option: %s\n", (op)); \
                      exit(2);

/* use MISSING (without parens) if output filename is missing */
#define MISSING fprintf(stderr, "missing output file\n"); \
                      exit(3);


#endif

Here is my output file when entering the phrase"hello" into the function:

Code    Char    Count
----    ----    -----
  0 NUL     1
  1 SOH     1
  2 STX     1
  3 ETX     1
  4 EOT     1
  5 ENQ     1
  6 ACK     1
  7 BEL     1
  8 BS      1
  9 HT      1
 10 LF      1
 11 VT      1
 12 FF      1
 13 CR      1
 14 SO      1
 15 SI      1
 16 DLE     1
 17 DC1     1
 18 DC2     1
 19 DC3     1
 20 DC4     1
 21 NAK     1
 22 SYN     1
 23 ETB     1
 24 CAN     1
 25 EM      1
 26 SUB     1
 27 ESC     1
 28 FS      1
 29 GS      1
 30 RS      1
 31 US      1
 32 SPC     1
 33 !       1
 34 "       1
 35 #       1
 36 $       1
 37 %       1
 38 &       1
 39 '       1
 40 (       1
 41 )       1
 42 *       1
 43 +       1
 44 ,       1
 45 -       1
 46 .       1
 47 /       1
 48 0       1
 49 1       1
 50 2       1
 51 3       1
 52 4       1
 53 5       1
 54 6       1
 55 7       1
 56 8       1
 57 9       1
 58 :       1
 59 ;       1
 60 <       1
 61 =       1
 62 >       1
 63 ?       1
 64 @       1
 65 A       1
 66 B       1
 67 C       1
 68 D       1
 69 E       1
 70 F       1
 71 G       1
 72 H       1
 73 I       1
 74 J       1
 75 K       1
 76 L       1
 77 M       1
 78 N       1
 79 O       1
 80 P       1
 81 Q       1
 82 R       1
 83 S       1
 84 T       1
 85 U       1
 86 V       1
 87 W       1
 88 X       1
 89 Y       1
 90 Z       1
 91 [       1
 92 \       1
 93 ]       1
 94 ^       1
 95 _       1
 96 `       1
 97 a       1
 98 b       1
 99 c       1
100 d       1
101 e       1
102 f       1
103 g       1
104 h       1
105 i       1
106 j       1
107 k       1
108 l       1
109 m       1
110 n       1
111 o       1
112 p       1
113 q       1
114 r       1
115 s       1
116 t       1
117 u       1
118 v       1
119 w       1
120 x       1
121 y       1
122 z       1
123 {       1
124 |       1
125 }       1
126 ~       1
127 DEL     1
        -----
Total           5

Where I am stuck is that every character says it appears once, regardless of how many times it actually appears. Thank you to anyone who can help, sorry this is such a long question.

Replace this:

if(shownArray[i] == (int)counter[i2])

With this:

if(i == counter[i2])

You want to use the index as the value being checked, not the number of times it has appeared. That comes later.

Also this:

for(i2=0;i2<=totalCount;i2++)

Should be this:

for(i2=0;i2<totalCount;i2++) // note strictly less-than

Just a add on change the below code :

prHeader(out);
if (out == NULL)
{
    printf("ERROR opening files. \n");
    return 1;
}

TO:

if (out == NULL)
{
    printf("ERROR opening files. \n");
    return 1;
}
else 
{
prHeader(out);
.
.
.
}

because if in case the FILE fails to open your checking NULL in header file function which will lead to runtime error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM