Thread: Searching through file for specific strings and adding values using array HELP?

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    34

    Searching through file for specific strings and adding values using array HELP?

    A patient database for people with OCD.
    I have a section of the text file in the format below for an entire month for one patient.

    January 1 Monday Brushing_teeth 9
    January 1 Monday Washing_hands 5
    January 1 Monday Twitching 6
    January 1 Monday Lock_checking 40
    January 2 Tuesday Brushing_teeth 10
    January 2 Tuesday Eating_hair 10
    January 2 Tuesday Twitching 10
    January 3 Wednesday Brushing_teeth 5
    January 3 Wednesday Grouping_food 3
    January 4 Thursday Brushing_teeth 6
    January 4 Thursday Washing_hands 10
    January 4 Thursday Washing_Face 5
    January 5 Friday Brushing_teeth 4
    January 5 Friday Grouping_food 4
    January 6 Saturday Brushing_teeth 7

    I would like to be able to search through the file and for each activity the person does, add the amount of times it is done every time it occurs, and avg per week and per month
    For eg. Brushing teeth 10
    .....
    .... brushing teeth 6

    then total would be 16 etc etc.
    If possible id like to know how to add the values using a parellel array or struct? below is my code

    Code:
    #include <stdio.h>
    
    int main()
    {
        
        char compulsions[30];
        char name[20];
       int patients=1;
       char month[10], day[10],comp[30];
       int date, reps;
    
    printf("Welcome to Track Me");
    
    
    // open the text file "comp.txt" for writing
    FILE *ptr;
    
    // open the file ".txt" for reading
    ptr = fopen("comp.txt", "r");
    if (ptr==NULL ){
        printf("File could not be opened");
    
    }
    
    fscanf(ptr,"%s",compulsions);
    printf("List of ALL 15 Compulsions\n");
           while(!feof(ptr)){
    
    printf("%s\n",compulsions);
    fscanf(ptr,"%s",compulsions);
    
           }
           fclose(ptr);
    
    
    fflush;
    //to search for patient file
    
    //for (patients=1; patients <=15; patients++)
    //{
    
    //printf("Enter Patients Name to access file");
    //scanf("%s",name);
    
    FILE *search;
    
    
    search = fopen("kristina.txt","r");
    if (search==NULL ){
        printf("File could not be opened");
    
    }
    
    
    
    while ( fscanf(search,"%s %d %s %s %d", month, &date, day, comp, &reps) > 4)
    
      printf("%s %d %s %s %d\n",month, date, day, comp, reps);
     //reps=reps+reps;
    
     printf("Total reps are", &reps);
    
    fclose(search);
           
    
    
    
               
    
    
           
           }
    one other problem is that id like the user to be able to enter the file name and upon the name given, the file would open. so far i just have a specific file in the fopen because using the variable for a name entered would not work.
    NOTE kristina.txt is the txt file holding all the information in the format above NOT comp.txt

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    Quote Originally Posted by Kristyy_mariee View Post
    one other problem is that id like the user to be able to enter the file name and upon the name given, the file would open. so far i just have a specific file in the fopen because using the variable for a name entered would not work.
    Okay, that is not so good because it should be fairly simple. Here's a simple program that reads the (text) file specified by name on the command line and prints it out:

    Code:
    #include <stdio.h>
    
    // C99 style declarations
    
    int main(int argc, const char *argv[]) {
    	if (argc < 2) {
    		puts("Filename required.");
    		return -1;
    	}
    
    	FILE *fh = fopen(argv[1], "r");
    	if (!fh) {
    		perror(argv[1]);
    		return -2;
    	}
    
    	char buffer[256];
    	while (fgets(buffer, 256, fh)) printf("%s", buffer);
    
    	fclose(fh);
    	return 0;
    }
    WRT your code, what is this, bedsides a compiler error:

    Code:
    fflush;
    It is very important that you test compile your code every few lines -- with warnings enabled.

    Quote Originally Posted by Kristyy_mariee View Post
    If possible id like to know how to add the values using a parellel array or struct?
    Do you have to load the compulsions from a file, or can you hard code them? If the former, this is somewhat trickier -- the simplest way would be to "brute force" it by creating either a parallel char/int array or a struct array of the compulsions, then using strcmp() for each line in the second file.
    Last edited by MK27; 11-26-2011 at 04:48 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    16
    With respect to your filename calling it should be something like this...

    Code:
    printf("Please enter filename: ");            
    scanf("%s", Your_Filename);
    
    
            Your_Pointer = fopen(Your_Filename,"r");


    Please note that your file should be in Visual studio => Projects => Your program name folder => Your program name folder.

    If it's not in there you won't be able to open it unless you put the file paths...

    Also note when entering the file name at the printf/scanf; you also need to enter the extension of the file. In your case it'd be .txt.

    Hence "filename.txt" is what would be entered and not "filename"

  4. #4
    Registered User
    Join Date
    Nov 2011
    Posts
    34
    from what I think youre trying to say...I dont think their hard coded if yu mean what i think you mean (fairly new to programming) i basically just have them listed in the file and then their just printed out to the screen. How would i go about putting them in an array then?

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    34
    Thanks so much, just addin on .txt when i entered the file name works

  6. #6
    Registered User
    Join Date
    Nov 2011
    Posts
    16
    Putting them in an array to read out on screen?

    First you have to print out the header, which I assume you would like to do?

    To print the header you use the fscanf with strings only (%s) and followed by the printf to print out the values. Would look something like this

    Code:
    #define num 100
    char var1 [num]
    char var2 [num]
    
    fscanf(Your_FilePtr,"%s %s ", var1, var2);
    printf ("%s %s\n", var1, var2);
    That should print out the header...of course I haven't added the semi-colon in certain things, I'll leave that for you

    You just need to change the declared variables to the headers of your file, and change them within your code as well...also add in extra headers since you've got 5 columns...

    So instead of var1/2
    You'd have Month, Date, Day, Compulsions, Repetitions etc...

  7. #7
    Registered User
    Join Date
    Nov 2011
    Posts
    34
    this is my code now
    Code:
    #include <stdio.h>
    #include <string.h>
    int main()
    {
        
       
        char name[20];
       int patients=1;
       char month[10], day[10],comp[30];
       int date, reps;
       int i;
    
    const int MAXSTRINGS = 16; // hold max of 10 strings
    
    const int MAXLENGTH = 50; // maximum of 50 characters per string
    
    char compulsions[MAXSTRINGS][MAXLENGTH];
    
    printf("Welcome to Track Me\n");
    
    
    // open the text file "comp.txt" for writing
    FILE *ptr;
    
    // open the file "comp.txt" for reading
    ptr = fopen("comp.txt", "r");
    
    if (ptr==NULL ){
        printf("File could not be opened");
    
    }
    
    
    //
    printf("List of ALL 15 Compulsions\n");
           while(!feof(ptr)){
    
    for(int i = 0; i < MAXSTRINGS; i++)
    
    {
        fscanf(ptr,"%s",compulsions[i]);
    printf("%s\n",compulsions[i]);
    
    
           
    }
           }
          fclose(ptr);
    
    
    fflush;
    //to search for patient file
    
    
    printf("Enter Patients Name to access file with extension .txt");
    scanf("%s",name);
    
    FILE *search;
    
    
    search = fopen(name,"r");
    if (search==NULL ){
        printf("File could not be opened");
    
    }
    
    
    
    while ( fscanf(search,"%s %d %s %s %d", month, &date, day, comp, &reps) > 4)
    
      printf("%s %d %s %s %d\n",month, date, day, comp, reps);
       if (!strcmp(comp, compulsions[1]))
       { printf("%d",reps);
       }
    
    
    fclose(search);
           
    
    
    
               
    
    
           
           }
    Ive tried to store the compulsions from comp.txt into an array and then when the other file is opened, i want to be able to compare compulsions from the array to the ones in the file and when the strings match perform a calculation to sum of all repetitions per compulsions.
    Eg,brushing teeth is compulsion 1 in comp.txt, so when i compare it with the compulsions in the other file if it matchs... how ever many times the person brushes their teeth would be added everytime the string matches as i go through the file.
    I tried to do it with the strcmp but when the program runs nothing happens. :/

  8. #8
    Registered User
    Join Date
    Nov 2011
    Posts
    16
    Unfortunately, I do not know how to do what you're trying to do, like yourself, I'm a newbie at C as well...but I'd also like to know how to do that ...
    Question though...why do you have ! infront of strcomp? Try removing that and see if something happens...

    Code:
    printf("%s %d %s %s %d\n",month, date, day, comp, reps);
    if (!strcmp(comp, compulsions[1])) { printf("%d",reps);
    }

  9. #9
    Registered User
    Join Date
    Nov 2011
    Posts
    34
    Oh lol, yehh i took it out, didnt change anything though

  10. #10
    Registered User
    Join Date
    Nov 2011
    Posts
    16
    Actually something does change, you're now getting a number instead of nothing....the question is..is the number what you're looking for..

    btw, I sent you a PM...
    Last edited by Spamtacus; 11-27-2011 at 12:26 PM.

  11. #11
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Ok, I'm watching this and a couple of other threads on the same problem...

    How long have you guys been studying C ? Is this like second year/first semester?

    The assignment seems awfully advanced for someone who's on their first semester...

    Are the full details of the assignment available? If so please post them here...

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Is this the assignment we're talking about?

    This is NOT a reasonable assignment for a seond program for first semester students... You guys should still be messing with for() loops and if()-else creating funny shapes on your screens or calculating repeative numbers... This is a full blown, real world application your teacher has assigned you... as a second program!

    In your place I'd be taking this to the Dean and complaining about it... this is 3rd semester, maybe second year stuff...


    UNIVERSITY OF THE WEST INDIES, CAVE HILL CAMPUS
    Department of Computer Science, Mathematics & Physics
    COMP1105 Computer Programming 1, Semester 1, 2011/2012
    Dr. Mechelle Gittens
    Mrs. Tessa-King Inniss

    Assignment #2

    Due: 4pm - Wednesday November 23rd - CMP Administrative Office

    In our first assignment we heard the story of Kay:

    There was a young lady named Kay
    Who brushed her teeth nine times each day.
    Her teeth, they would last,
    But toothpaste went fast
    With 279 brushings in May

    You are now required to implement your algorithm in the C-language with several important
    modifications required by the doctor. The modifications are underlined so that they are clear to you
    the software developer.

    After the events of May and the previous months. Kay realised that she had a compulsive need to
    brush and do other tasks in her every day activities. She decided to visit a psychologist for a remedy
    for this condition.

    On visiting Dr. Lee Counsellory, she was diagnosed with Obsessive Compulsive Disorder or OCD.
    Obsessive Compulsive Disorder is a disorder of the brain and behavior. OCD causes severe anxiety in
    those affected. OCD involves both obsessions and compulsions that take a lot of time and get in the
    way of important activities the person values.

    As part of Kay's treatment, Dr. Counsellory has commissioned your software consulting firm to design
    and implement a software application that can be used to track the activities of people with OCD, so
    that he can determine if his primary treatments (pharmaceuticals, hypnosis and/or assisted therapy)
    are helping their condition.

    The application must let a nurse enter information for a number of patients about the patients' number
    of repetitions for various otherwise ordinary activities. The activity information is recorded by each
    patient in a simple text file with the following format:

    Month Date Day Activity Repetitions
    January 1 Monday brushed_teeth 9
    January 1 Monday combed_hair 5
    January 1 Monday stepped_up_bottom_step 20
    January 1 Monday cleaned_basin 40
    January 2 Tuesday brushed_teeth 10
    January 2 Monday combed_hair 10
    January 2 Monday stepped_up_bottom_step 10
    January 2 Monday cleaned_basin 20

    The text files are all emailed to the nurse at the doctor's office at the end of the month. The nurse
    enters the information on the morning of the first day of the next month after all of the patients have
    sent in their email.

    The activities that may be repeated may include but are not limited to brushing teeth, ironing a single
    piece of clothing, cleaning a single item, washing hands, combing/brushing hair and all other distinct
    daily tasks - for many patients. However you may assume that there are no more than 30 possible
    compulsions performed by all patients under Dr. Counsellory's care.

    The following are the details of the requirements of the application.
    1. The application is called TrackMe. It must present a greeting to the nurse when the application
    starts.
    2. The patient must specify the month in which they recorded their information so that the nurse
    can ensure that the information is being entered for only one month for all the patients,
    3. The patient will record the information in their text file in the manner specified above.
    4. The application must read the month, date, day, activity and repetitions and process it toward
    the necessary summary.
    5. The application must give a final summary of how many times each activity was done on
    average per day over the month for each patient.
    6. The application must give a final summary of how many times each activity was done on
    average per week over the month for each patient.
    7. The application must give a final summary of how many times each activity was done for a given
    month for a given patient.
    8. The application must output each patients' first name, last name and patient ID at the beginning
    of the summary of their activity.
    9. The application must maintain the names of all patients with any compulsions performed over
    20 times in a day on any day. These patients will require special treatment and must be
    highlighted to the doctor in the summary at the end. The doctor limits his treatment of patients
    with OCD to a maximum of 30 patients so that he can be attentive to their needs.
    10. The application must maintain the names of all patients with all compulsions performed less
    than 4 daily on each day. These patients do not require further treatment and will require a
    completion visit with the doctor.

    TrackMe must ask for the name of a text file to read from the nurse for
    a patient until that nurse states that there is no more data for the
    patients.

    It is reasonable to assume that the client does not perform any more
    than 30 distinct repetitive activities.

    You are required to develop a COMPLETE documented C-language
    solution for TrackMe.



    Items for submission: You MUST use functions (at least two), parallel arrays, and file processing in your
    solution. Your submitted solution MUST include:

    1. A typed documented pseudocode algorithm document. [25 marks]
    2. C-language documented program included as a .vcproj file with a .cpp file and any included .c
    files. Make sure that this can be opened on a computer in one of the labs on
    campus and not just on your personal computer. [50 marks]
    3. Sample data in files for two patients and two desk traces. The sample data
    need only cover up to 10 compulsions per patient. [10 marks]
    4. A printed manual that describes how to use your program, with steps
    demonstrated with screen captures. [10 marks]

    Items 1 – 5 should be included on a CD, and items 1, 4, 5 should be included in printed paper format. If
    you make any assumptions please note these assumptions in your solution. Do not make assumptions
    that attempt to change the requirements. [2 marks]

    Your solution must be submitted to the CMP Department main office as specified above, in a 8 ½ “ x
    11” or 8 ½ “ x 14” envelope, with your name, student number, the course name and number, your
    instructors name, the assignment number, your email address all written on the envelope, and printed
    on your program manual. [1 marks]

    Your solution must be typed [2 marks]. There will be NO email submission for this assignment. (If you
    have responsibilities that may interfere with your submission time, then try submitting your assignment
    early.) Late policy: 1 day late - mark/2; 2 days late – mark/4; more than 2 days late NOT ACCEPTED.

    State all assumptions, but do not presume. If you are unclear, ask questions.
    This coursework assignment is worth 10% out of 40%
    Bonus Question: 25 marks
    For those patients with compulsions executed over 20 times the doctor wants to offer them a simple
    computer game to play for relaxation. You are therefore asked to use parallel arrays to create a simple
    documented tic-tac-toe game program that will:
     Display the tic-tac-toe board layout
     Allow the user to select a player
     Get a valid player square selection within the limits of the board
     Get the row index for a the square and then the column index of a square
     Insert the relevant X or O
     Repeat and check for a winner and display the necessary message
     End the game when board filled
    Your work is valuable, so good luck!

    "Computer science is a dynamic field in which you can combine your creativity with your skills in communication,
    mathematics and logic. It will give you a degree that is highly employable in whatever industry you choose. And, by studying
    and pursuing a career in computer science, you can help to determine the ways that computers will enrich peoples’ lives in
    the future." - University of Calgary, Computer Science Admissions Booklet
    Last edited by CommonTater; 11-27-2011 at 03:50 PM.

  13. #13
    Registered User
    Join Date
    Nov 2011
    Posts
    34
    I agree because this the first course for programming at the university, but its due Thursday and me and the people in my class havent even started on the calculations for this thing

  14. #14
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Kristyy_mariee View Post
    I agree because this the first course for programming at the university, but its due Thursday and me and the people in my class havent even started on the calculations for this thing
    I do feel sorry for the lot of you... that is one nasty second assignment...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 11-11-2011, 05:49 PM
  2. picking out specific values from an array
    By jak9 in forum C Programming
    Replies: 7
    Last Post: 10-13-2010, 01:05 PM
  3. Searching a specific string/word/etc in a text file?
    By zacharyrs in forum C Programming
    Replies: 5
    Last Post: 11-29-2009, 07:54 PM
  4. Adding Values Of An Array
    By moenia in forum C++ Programming
    Replies: 2
    Last Post: 05-12-2003, 02:32 PM
  5. searching for a specific item in a C++ file
    By stanleyw in forum C++ Programming
    Replies: 1
    Last Post: 06-03-2002, 04:54 PM

Tags for this Thread