Thread: Specifc Character Counts

  1. #1
    Registered User
    Join Date
    Sep 2014
    Posts
    13

    Specifc Character Counts

    Hello,

    I am a beginning student learning C programming. I am having trouble understanding an application problem that was given to me. It requests the user to do the following:

    [1] Ask the user for the name of a file, in this case a .txt file.
    [2] The program should go through the file, character by character and keep a running total of how many times each of the 26 letters are used.
    [3] Output the characters, with their counts, in order.

    Example Input: Apple
    Example Output:

    P 2
    A 1
    L 1
    E 1

    Here is my code:
    Code:
    #include <stdio.h>
    #include <string.h>
    
    FILE *inFile;
    
    int main() {
       char fileName[100];
       char myChar;
    
       printf("Enter filename (include .txt at the end): ");
       scanf("%s", fileName);
    
       inFile = fopen(fileName, "r");
       if (inFile == NULL) {
          printf("Not available");
          return -1;
       }
       else {
          while(!feof(inFile)) {
             fscanf(inFile, "%c", &myChar);
             printf("%c \n", myChar);
          }
       fclose(inFile);
       }
       return 0;
    }
    What I am having trouble with is [2]. Any help would be appreciated.
    Last edited by ZeroBoyd; 11-20-2014 at 05:51 PM.

  2. #2
    Registered User Al3's Avatar
    Join Date
    Nov 2014
    Posts
    135
    It will be easier if you actually point out what exactly you have trouble understanding with. Like that, we assume you can't understand the entire code which would be something you should pay attention to.


    • First two lines, you include the standard input-output librariy and the library that provide string operations.


    • Then you declare a variable type FILE pointer. FILE is type-defed structure.


    • Then, in the main-entry function (seems you are using GCC) You declare a variable type "char array" with 100 items and another simple variable type "char"


    • You use the io function printf, to print some text that asks the user to type the name of the file x

    • Then, you use the io function scanf that request a string (user stdin input) and store it into the char array variable.


    • Then you open a file stream in the FILE* variable using the io function fopen, that opens the text file x using "r" attribute, which stands for READ rights.


    • Then you have a condition that checks if the file is empty and if it is, the function quits with status -1 (error) and prints a failure text. If it is not empty:


    • You use "while" loop that will run until the io function feof function returns EOF (End Of File) (EOF indicator is reached when the indicator/cursor reached the end of the file)


    • Inside the loop you take all the characters, storing them in the variable of type "char" and print that character out, passing new line character escape sequence after each.


    • When the loop ends, you use the io function fclose that closes the file opened. And terminate the function.
    Last edited by Al3; 11-20-2014 at 05:46 PM.

  3. #3
    Registered User
    Join Date
    Sep 2014
    Posts
    13
    What I am having trouble with is the running total of the number of times the letters are repeated.

  4. #4
    Registered User Al3's Avatar
    Join Date
    Nov 2014
    Posts
    135
    Oh so, that is the code you wrote so far? It is not what you want.
    First of all, use fgetc function instead of fscanf. fgetc is dedicated for that purpose. No actually wait. Let me write a quick program for you.
    The maximum is 26 letters ?

  5. #5
    Registered User
    Join Date
    Sep 2014
    Posts
    13
    My assumption was Upper and Lower case letters should be combined (e.g A and a should be treated as A). Limit is the 26 letter alphabet.

  6. #6
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    @Al3:
    Please don't write programs for people. It's against this forum's homework policy and it prevents people from really learning to think throug and solve problems and program (which is the point of this forum, after all); it only teaching them to copy-paste somebody else's solution.

    @ZeroBoyd:
    Can you be more specific in what you don't understand? Also, it may help to step away from the keyboard and get the paper and pencil. Think about how you might do this if I asked you to count the occurrences of each letter with a piece of paper and pencil. You wouldn't simply look at a letter then echo it back out, then move to the next letter. Try doing this by hand with a few short pieces of text like a brief poem or quote.

    EDIT: And for the upper/lower case stuff, I can't say if your assumption is valid (though it seems reasonable), you would need to ask your instructor to be certain. If so, you can look into the toupper/tolower functions, just make sure you #include <ctype.h> if you're going to use them.

  7. #7
    Registered User Al3's Avatar
    Join Date
    Nov 2014
    Posts
    135
    Okay. I am done. (It is 02:16 AM here, tomorrow I have important exams so I won't advance it much). But what I have for you is extremely fast, memory-sparing and short algorithm for counting characters without any limits.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    int main(void) // <-- No main input parameters will be used
    {
        FILE* fp;
        char fileName[128], lookupTable[128] = {0};
        int currentChar;
    
    
        printf("Enter file name (Appending the extension (.txt)): "); scanf("%s", fileName);
        if(!(fp = fopen(fileName, "r")))
        {
            printf("Error opening file: %s\n", fileName);
            return EXIT_FAILURE;
        }
    
    
        while((currentChar = fgetc(fp)) != EOF)
        {
            lookupTable[currentChar]++;
        }
    
    
        for(currentChar = 0; currentChar != 128; currentChar++)
        {
            printf("%c\t:\t%i\n", currentChar, lookupTable[currentChar]);
        }
        fclose(fp);
        return EXIT_SUCCESS;
    }
    It lists each character and how many occurrences are in the text file specified. Since you have the base algorithm, you can play a bit with it and easily restrict it and fit it on your taste.
    @anduril462 Too late.. But thats the reason why I didn't do his homework. Just provided him a good example of how he can do that. From now on, he needs to fit it on the way he like it. I won't even explain the code.
    Last edited by Al3; 11-20-2014 at 06:24 PM.

  8. #8
    Registered User
    Join Date
    Sep 2014
    Posts
    13
    Quote Originally Posted by anduril462 View Post
    @ZeroBoyd:
    Can you be more specific in what you don't understand? Also, it may help to step away from the keyboard and get the paper and pencil. Think about how you might do this if I asked you to count the occurrences of each letter with a piece of paper and pencil. You wouldn't simply look at a letter then echo it back out, then move to the next letter. Try doing this by hand with a few short pieces of text like a brief poem or quote.

    EDIT: And for the upper/lower case stuff, I can't say if your assumption is valid (though it seems reasonable), you would need to ask your instructor to be certain. If so, you can look into the toupper/tolower functions, just make sure you #include <ctype.h> if you're going to use them.
    Regarding the assumption, I did ask my Instructor about this and she said "Follow what you think the assignment says. You will find out after Thanksgiving when I work the problem myself." While this is considered homework, and it was for me when I submitted it Sunday, I want to know what I was getting wrong. I won't find out until weeks after and that would be my grade, not the solution.

    In specifics (as far as I can word), what I don't understand is how to compute switching between characters and calculating how many times that character existed in a word.

  9. #9
    Registered User Al3's Avatar
    Join Date
    Nov 2014
    Posts
    135
    I wrote you a good example, compile it... identify it.. you will be a programmer. What kind of programmer you'll be if you can't even identify native 29 lines of code..

  10. #10
    Registered User
    Join Date
    Sep 2014
    Posts
    13
    From what the code "looks like" it is just printing a list of characters between 0 and 127. Don't know what the difference between fscanf and fgetc is nor do I know what %i is for, but thats what the Internet is for. Thank you for example.

    EDIT: I know by now that I don't want to be a Programmer. It takes to many hours in the day to do one complex problem, way to ineffienct.
    Last edited by ZeroBoyd; 11-20-2014 at 07:09 PM.

  11. #11
    Registered User Al3's Avatar
    Join Date
    Nov 2014
    Posts
    135
    Umm.. the program I wrote to provide you an example does way more then printing characters between 0 and 127. It also does what you wanted, counting each character occurrences.
    "%i" is a mode specifier for printf-like functions. It requests integer. I usually prefer %i then %d (which is more commonly used) Because for me it makes more sense as a shorten name.
    What did you expected? Complex programs in minutes? Because thats the opposite of what you complaint of.......

  12. #12
    Registered User
    Join Date
    Sep 2014
    Posts
    13
    AI3, I am sorry if it turned out negative. I am very thankful for the example, you did more than what my Instructor did which is take time to try and teach me a concept. EDIT: As you have exams you can ignore this thread. It is not an urgent thing as I have till Thanksgiving Breaks end to figure it out. If I am still having trouble I will hound my Instructor to explain it.

    Take in mind I am a High School student taking a Intro to C class. A complex problem at this level took me 20+ hours of work before I reached the deadline. I posted this on cBoard as a chance to learn the concept from a group of programmers. If, out in the real world or college level, that a complex problem at their respective level it would take me days. I do not make a good programmer based upon results, hence why I am not pursuing it.

    In your code it used two new things that I was unfamiliar with: %i which you explained above and fgetc. I am currently reading on fgetc, and according to my class lesson plan it won't be talked about until the Spring.
    Last edited by ZeroBoyd; 11-20-2014 at 07:50 PM.

  13. #13
    Registered User Al3's Avatar
    Join Date
    Nov 2014
    Posts
    135
    I just wish I had C in school. I would be really thankful. Here in Bulgaria we have only a very few (CPE - Center for Professional Education) and even less that offer C as a language.
    I paid 2000 BGN to participate in the course.

    One more thing.. You can't think of being able to program only with knowledge. (Hell you don't even have the knowledge yet).
    The knowledge is required as minimum, to be able to program. What follows is the LOGIC. The only thing that increases logic is - practice. A lot of. THEN ..you will start reducing your concerns, concerns.. similar to the one you have right now.

    How do you think I found the way to make this program? Logic. The built.. is with knowledge.
    I'm glad in 29 lines you could find only 2 things you didn't know of.
    Wise words I learned: With knowledge, you can answer to the questions: What and Why
    With logic, you can answer to the questions: How and When
    Think of it.
    Last edited by Al3; 11-20-2014 at 08:02 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. adjusting character counts for utf8
    By MK27 in forum C Programming
    Replies: 32
    Last Post: 02-03-2009, 07:07 PM
  2. words counts
    By lingz82 in forum C++ Programming
    Replies: 3
    Last Post: 08-31-2006, 05:16 AM
  3. about program that counts a character frequency
    By Unregistered in forum C++ Programming
    Replies: 15
    Last Post: 04-23-2002, 01:21 PM
  4. post counts...
    By ober in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 02-04-2002, 09:50 PM