Thread: I need help with a for loop in my string processing code.

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    308

    I need help with a for loop in my string processing code.

    I can split the input into sentences that end with a period.
    I can split the sentence into individual words.
    I can remove the null strtok puts on and so I can use a for loop.

    Why I want to use a for loop is each loop processes a single sentence.
    When the sentence is processed in becomes individual words,
    and then a percentage that's written into a file.
    After the sentence is written to file as a percentage I want to loop
    back and get another sentence, until the source is empty.

    Here's my unanswered questions I need to know to solve my problem:

    I plan to use a for loop.
    1) I don't know if I'm looping through b or the single sentence in pch?
    2) I don't know how to increment the for loop, do I use a int and a new variable?.
    3) I don't know how to break out of the for loop. One the loop is finished a if statement tests to see if the count is \0,
    but I'm not sure on the specifics.

    I was going to try to use Adaks code, but after reading about strtok I found the problem was it makes the original string have NULL.
    My technique of using strpbrk fixes that.
    I'm semi-sure that my solution of using a for loop can let me process individual sentences, but I'm not sure on how to do it. Because Adak may want to see what I did with his code I will post that after I post the code I'm working and and made the thread for.

    The code I need help with:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
     
    /* function prototype to count the number of characters in a string */
    int countchar (char []);
    /* function prototype to find the first and last letter in the word */
    char find_letter (char* a, char* b);
    char red;
    /* function prototype to reverse the letters in the word */
    char* rev(char* str);
    char* reverse;
    /* function so I don't have to type getch all over the place */
    void MyExit(void) { system("pause"); }
      
    /* the main program */
      
    int main ()
    {
        /* declaring and initiaizing variables */
        FILE *sp;
        FILE *fp;
        char *filedata = malloc(300);
        char str2[7];
        char * pch = malloc(300);
        char vowels[] = "aeiouy";
        char letters[] = "bcdfghjklmnpqrstvwxz";
    	char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
        char *b = malloc(sizeof(char)*1000);
        float one;
        float two;
        float three;
        float four;
        float total;
        float five;
        float six;
        float seven;
        float eight;
        float total_2;
        float percentage_1;
        float percentage_2;
        float percentage_3;
        float percentage_4;
        int numchar;
        one = 0;
        two = 0;
        three = 0;
        four = 0;
        total = 0;
        five = 0;
        six = 0;
        seven = 0;
        eight = 0;
        total_2 = 0;
        percentage_1 = 0;
        percentage_2 = 0;
        percentage_3 = 0;
        percentage_4 = 0;
        atexit(MyExit);
        /* open text file or report error */
       sp = fopen("readlist.txt", "r");
       fp = fopen("writelist.txt", "w");
     
        if(!sp)
        {
        perror("Error: file readlist.txt was not found or opened");
        return 0;
        }
        if((fp = fopen("writelist.txt", "w"))==NULL) {
        printf("Cannot open file.\n");
        exit(1);
        }
     
      /* input sentence */
      
      printf("Input a short sentence: ");
      gets(b);
      pch = strtok (b, ".");
       /* I tokenize the input string into individual sentences */
      while(pch != NULL)
        {
    		pch = strtok (NULL, ".");
      }
      /* pch is NULL, so I find alphabet in b and pass that into pch */
      pch = strpbrk(b, alphabet);
      /* I tokenize the input string into individual words */
      pch = strtok (b, " ");
        /* numchar counts the numbers of characters in the pch string */
     numchar = countchar (pch);
      /* The while loop gives value to five, six, seven, eight, which is used for the percentage calculation */
      while(pch != NULL)
        {
            /* text file comparison begin */
            while(fgets(filedata, 300, sp))
            {
                if(_memicmp(pch, filedata, strlen(pch)) == 0
                    && (filedata[strlen(pch)] == ' '
                    || filedata[strlen(pch)] == '\n'))
                {
                    /* adding numchar to filedata erases the word and leaves the grammar intact */
                    printf("%s\n%s\n", pch, filedata+numchar+1);
                    /* write the text file comparison result to file */
                    fprintf(fp, "%s\n%s\n", pch, filedata+numchar+1);
                }
            }
            /* text file comparison end */
             
            /* identify the first and last letter in the word begin */
             
            red = find_letter(str2, pch);
            if(strpbrk(str2, letters))
            {
            one++;
            }
            if(strpbrk(str2, vowels))
            {
            two++;
            }
     
            reverse = rev(pch);
     
            red = find_letter(str2, pch);
            if(strpbrk(str2, letters))
            {
            three++;
            }
            if(strpbrk(str2, vowels))
            {
            four++;
            }
            /* identify the first and last letter in the word end */
            /* The math to see what kind of word it is start */
             
            if(total = (one && three))
            {
            five++;
            }
            else if(total = (one && four))
            {
            six++;
            }
            else if(total = (two && three))
            {
            seven++;
            }
            else if(total = (two && four))
            {
            eight++;
            }
            /* The math to see what kind of word it is end */
     
            /* Reset the pointers */
            one = 0;
            two = 0;
            three = 0;
            four = 0;
            total = 0;
            rewind(sp);
     
        pch = strtok (NULL, " ");
      }
    
      /* pch is NULL, so I find alphabet in b and pass that into pch */
      pch = strpbrk(b, alphabet);
      /* pch is backwards, so I use rev to reverse it back */
      /*printf("%s uncomment to test to see if the string is backwards", pch);*/
      reverse = rev(pch);
      /* count the pointers */
      total_2 = (five + six + seven + eight);
      percentage_1 = ((five)/ total_2);
      percentage_2 = ((six)/ total_2);
      percentage_3 = ((seven)/ total_2);
      percentage_4 = ((eight)/ total_2);
      printf("\nletter vowel letter %f\nletter vowel vowel %f\nvowel vowel letter %f\nvowel vowel vowel %f\n", percentage_1, percentage_2, percentage_3, percentage_4);
      /* write the pointers result to file */
      fprintf(fp, "\nletter vowel letter %f\nletter vowel vowel %f\nvowel vowel letter %f\nvowel vowel vowel %f\n", percentage_1, percentage_2, percentage_3, percentage_4);
      fclose(fp);
      return 0;
    }
     
    /* The function to find the first letter in the word */
    char find_letter (char* a, char* b)
    {
        char string = strlen(b);
        strncpy (a,b,1);
        a[1]='\0';
        return 0;
    }
      
    /* The function to reverse the characters in a string */
    char* rev(char* str)
    {
      int end= strlen(str)-1;
      int start = 0;
      
      while( start<end )
      {
        str[start] ^= str[end];
        str[end] ^=   str[start];
        str[start]^= str[end];
      
        ++start;
        --end;
      }
      
      return str;
    }
     
    /* The function to count the number of characters in a string */
     
    int countchar (char list[])
    {
        int i, count = 0;
        for (i = 0; list[i] != '\0'; i++)
            count++;
        return (count);
    }
    Adak's code I tweaked. I'm not posting for help with this code:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <ctype.h>
      
    int main (void) {
       int character, J, len;
       char string[]= {"There. is 10, 9daysaway! forest.."};
     
       printf("%s\n\n",string);
            
       J=0;
       len = strlen(string)+1;
       for(character=0;character<len;character++)
       {
            if(string[character]=='\n')
            putchar('\n');
            if((isalnum(string[character]))||(ispunct(string[character])))
            {
                 if(string[character+1]==' ' || string[character+1]=='\n'|| string[character+1]=='.'|| string[character+1]==','|| string[character+1]=='!')
                 {
                                           putchar(string[character]);
                                           putchar('\n');
                 }
                 if(J==0)
                 putchar(string[character]);
                 else
                 strlen(string);
                 ++J;
            }
            else
            {
                 J=0;
            }
      
       }
       printf("\n\n");
       getch();
       return 0;
    }
    I'm stuck, so if you don't answer me outright, which I know you people don't like to do, then give me some code that will get me going again because right now I'm stuck.

  2. #2
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    While I was waiting for a reply I read a thread and a post by anduril462. He said to use functions. So I looked at my code in the first post and saw it was a mess in the main function so I made my code into a function and passed that into the main function.

    Now the main function is really clean and easy to understand.

    Here is my new code:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
     
    /* function prototype for percentage calculation */
    char percentage_calculation_numbers(char*, int, char*);
    /* function prototype to count the number of characters in a string */
    int countchar (char []);
    /* function prototype to find the first and last letter in the word */
    char find_letter (char* a, char* b);
    char red;
    /* function prototype to reverse the letters in the word */
    char* rev(char* str);
    char* reverse;
    /* function so I don't have to type getch all over the place */
    void MyExit(void) { system("pause"); }
      
    /* the main program */
      int numchar;
    int main ()
    {
        /* declaring and initiaizing variables */
        char * pch = malloc(300);
        char *b = malloc(sizeof(char)*1000);
        char alphabet1[] = "abcdefghijklmnopqrstuvwxyz";
        
        atexit(MyExit);
     
      /* input sentence */
      
      printf("Input a short sentence: ");
      gets(b);
      pch = strtok (b, ".");
       /* I tokenize the input string into individual sentences */
      while(pch != NULL)
        {
    		pch = strtok (NULL, ".");
      }
      /* pch is NULL, so I find alphabet in b and pass that into pch */
      pch = strpbrk(b, alphabet1);
      /* I tokenize the input string into individual words */
      pch = strtok (b, " ");
        /* numchar counts the numbers of characters in the pch string */
     numchar = countchar (pch);
     /* I calculate the percentage */
     percentage_calculation_numbers(pch, numchar, b);
    
      return 0;
    }
     
    /* The function to find the first letter in the word */
    char find_letter (char* a, char* b)
    {
        char string = strlen(b);
        strncpy (a,b,1);
        a[1]='\0';
        return 0;
    }
      
    /* The function to reverse the characters in a string */
    char* rev(char* str)
    {
      int end= strlen(str)-1;
      int start = 0;
      
      while( start<end )
      {
        str[start] ^= str[end];
        str[end] ^=   str[start];
        str[start]^= str[end];
      
        ++start;
        --end;
      }
      
      return str;
    }
     
    /* The function to count the number of characters in a string */
     
    int countchar (char list[])
    {
        int i, count = 0;
        for (i = 0; list[i] != '\0'; i++)
            count++;
        return (count);
    }
    
    /* The function for percentage calculation */
    char percentage_calculation_numbers(char* a_pch, int a_numchar, char* a_b)
    {
        FILE *sp;
        FILE *fp;
        char *filedata = malloc(300);
        char str2[7];
        char vowels[] = "aeiouy";
        char letters[] = "bcdfghjklmnpqrstvwxz";
    	char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
        float one;
        float two;
        float three;
        float four;
        float total;
        float five;
        float six;
        float seven;
        float eight;
        float total_2;
        float percentage_1;
        float percentage_2;
        float percentage_3;
        float percentage_4;
        
        one = 0;
        two = 0;
        three = 0;
        four = 0;
        total = 0;
        five = 0;
        six = 0;
        seven = 0;
        eight = 0;
        total_2 = 0;
        percentage_1 = 0;
        percentage_2 = 0;
        percentage_3 = 0;
        percentage_4 = 0;
        
        /* open text file or report error */
       sp = fopen("readlist.txt", "r");
       fp = fopen("writelist.txt", "w");
     
        if(!sp)
        {
        perror("Error: file readlist.txt was not found or opened");
        return 0;
        }
        if((fp = fopen("writelist.txt", "w"))==NULL) {
        printf("Cannot open file.\n");
        exit(1);
        }
        
        /* The while loop gives value to five, six, seven, eight, which is used for the percentage calculation */
      while(a_pch != NULL)
        {
    	 /* text file comparison begin */
            while(fgets(filedata, 300, sp))
            {
                if(_memicmp(a_pch, filedata, strlen(a_pch)) == 0
                    && (filedata[strlen(a_pch)] == ' '
                    || filedata[strlen(a_pch)] == '\n'))
                {
                    /* adding numchar to filedata erases the word and leaves the grammar intact */
                    printf("%s\n%s\n", a_pch, filedata+numchar+1);
                    /* write the text file comparison result to file */
                    fprintf(fp, "%s\n%s\n", a_pch, filedata+numchar+1);
                }
            }
            /* text file comparison end */
             
            /* identify the first and last letter in the word begin */
             
            red = find_letter(str2, a_pch);
            if(strpbrk(str2, letters))
            {
            one++;
            }
            if(strpbrk(str2, vowels))
            {
            two++;
            }
     
            reverse = rev(a_pch);
     
            red = find_letter(str2, a_pch);
            if(strpbrk(str2, letters))
            {
            three++;
            }
            if(strpbrk(str2, vowels))
            {
            four++;
            }
            /* identify the first and last letter in the word end */
            /* The math to see what kind of word it is start */
             
            if(total = (one && three))
            {
            five++;
            }
            else if(total = (one && four))
            {
            six++;
            }
            else if(total = (two && three))
            {
            seven++;
            }
            else if(total = (two && four))
            {
            eight++;
            }
            /* The math to see what kind of word it is end */
     
            /* Reset the pointers */
            one = 0;
            two = 0;
            three = 0;
            four = 0;
            total = 0;
            rewind(sp);
            a_pch = strtok (NULL, " ");
      }
    
      /* pch is NULL, so I find alphabet in b and pass that into pch */
      a_pch = strpbrk(a_b, alphabet);
      /* pch is backwards, so I use rev to reverse it back */
      /*printf("%s uncomment to test to see if the string is backwards", pch);*/
      reverse = rev(a_pch);
      /* count the pointers */
      total_2 = (five + six + seven + eight);
      percentage_1 = ((five)/ total_2);
      percentage_2 = ((six)/ total_2);
      percentage_3 = ((seven)/ total_2);
      percentage_4 = ((eight)/ total_2);
      printf("\nletter vowel letter %f\nletter vowel vowel %f\nvowel vowel letter %f\nvowel vowel vowel %f\n", percentage_1, percentage_2, percentage_3, percentage_4);
      /* write the pointers result to file */
      fprintf(fp, "\nletter vowel letter %f\nletter vowel vowel %f\nvowel vowel letter %f\nvowel vowel vowel %f\n", percentage_1, percentage_2, percentage_3, percentage_4);
      fclose(fp);
    }
    I could still use some help in the main function with that for loop though.

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    It's hard to figure out what's going on with your code. This is an example:
    Code:
      /* input sentence */
      
      printf("Input a short sentence: ");
      gets(b);
      pch = strtok (b, ".");
       /* I tokenize the input string into individual sentences */
      while(pch != NULL)
        {
    		pch = strtok (NULL, ".");
      }
    The length of the string, should be the length of the sentence, so why put in code to detect the length of the sentence? Just strlen() the char variable that is holding the sentence the user entered.

    It's great having the functions, but now can you clean up the logic?

    As this project gets longer, you're going to have to find smarter ways to work to debug it. The warning from here is, simplify your code, simplify your logic. As code gets longer and more involved, the work needed to debug it goes up almost exponentially. Easy fixes seem to melt away like Frosty the Snowman on a hot Spring day.

    Why are you reversing the strings?

  4. #4
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    Quote Originally Posted by Adak View Post

    The length of the string, should be the length of the sentence, so why put in code to detect the length of the sentence?

    Why are you reversing the strings?
    First answer is I will paste a free book in at once. That's thousands of sentences.
    Each sentence I want a result written to the text file.
    How I was going to try and do this is have the book input, then feed the program a sentence at a time using the strtok "." and loop through the book a sentence at a time using a for loop.

    But according to you the string is supposed to be only one sentence, so I can't feed in the book as I just described.

    Why reverse the string?
    The first char of the word is compared to the vowels and letters arrays. Then the word is reversed and the last letter is now the first char so it can now be compared to the vowels and letters arrays to see which it belongs to.

    I think I am happy with the way the logic is now. The main function is easy to read, the functions are easy to understand, everything works.
    When I learn more C language then I can improve how the logic looks, if I want to that is.

    So you say the string should be only one sentence? Then this thread is finished as there is no solution for what I want to do.
    But thank you Adak, this also simplified my job because not I can focus on the next step.

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by jeremy duncan View Post
    First answer is I will paste a free book in at once. That's thousands of sentences.
    I pretty much have figured out what a book consists of, thanks.

    Each sentence I want a result written to the text file.
    How I was going to try and do this is have the book input, then feed the program a sentence at a time using the strtok "." and loop through the book a sentence at a time using a for loop.

    But according to you the string is supposed to be only one sentence, so I can't feed in the book as I just described.
    NO, that's not what I said. That's what YOU said I said - and way off the mark.

    The easy way to read in a book, is to do it row by row, with fgets(). It's a beautiful function for it, and a simple while loop, does it all:

    Code:
    while((fgets(buffer, sizeof(buffer), file Pointer)) != NULL) {
       //all your code in here to handle each row of text.
    
    }
    Why reverse the string?
    The first char of the word is compared to the vowels and letters arrays. Then the word is reversed and the last letter is now the first char so it can now be compared to the vowels and letters arrays to see which it belongs to.

    I think I am happy with the way the logic is now. The main function is easy to read, the functions are easy to understand, everything works.
    When I learn more C language then I can improve how the logic looks, if I want to that is.

    So you say the string should be only one sentence? Then this thread is finished as there is no solution for what I want to do.
    But thank you Adak, this also simplified my job because not I can focus on the next step.
    No, I did not say that. There are several ways to do what you want, and clearly, I do not understand the way you want to do this.

    Let me exit stage right, and there will be less confusion. Carry on, and good luck.

  6. #6
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    Hi Adak,

    I did not understand you before and misquoted you, I'm sorry.

    Here is the code I will try when I get back to my computer:

    Code:
    #define LINES 1024 
    int main ()
    {    
    /* declaring and initiaizing variables */   
    FILE *book; 
    char buffer[LINES];
    char * pch = malloc(300);    
    char *b = malloc(sizeof(char)*1000);    
    char alphabet1[] = "abcdefghijklmnopqrstuvwxyz";         
    atexit(MyExit);    
    
    /* open text file or report error */   
    book = fopen("readtext.txt", "r");
    
    if(!book)    
    {    
    perror("Error: file readtext.txt was not found or opened");    
    return 0;    
    }
    
    /* input sentence */ 
    if (book != NULL) {
    while((fgets(buffer, sizeof(LINES), book)) != NULL) 
    {  
    /* I tokenize the input string into individual words */  
    pch = strtok (b, " ");    
    
    /* numchar counts the numbers of characters in the pch string */ 
    numchar = countchar (pch); 
    
    /* I calculate the percentage */ 
    percentage_calculation_numbers(pch, numchar, b); 
    } 
    fclose(book);
    }
    
    return 0;
    }
    How does that look to you? Don't get angry because I misunderstood you, I don't want to offend you since your the only person here who talks to me, CommonTater and nobody never replies to me anymore. So, don't get angry, please.

  7. #7
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    No worries, Jeremy.

    That looks like a great start to your program. I believe if you follow logic similar to how you would do this with paper and pencil, you'll be fine. If Rube Goldberg comes knocking on your door - DON'T LET HIM IN!

  8. #8
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    Here is the code I made:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define LINES 1024 
    void MyExit(void) { system("pause"); }
    int main ()
    {    
         /* declaring and initiaizing variables */
         FILE *book;
         char buffer[LINES];
         atexit(MyExit);     
         
         /* open text file or report error */
         book = fopen("readtext.txt", "r"); 
         
         if(!book)    
         {    
              perror("Error: file readtext.txt was not found or opened");    
              return 0;    
         } 
         
         /* read from file */
                  while(fgets(buffer, sizeof(LINES), book)!=NULL) 
                  {  
                                      printf("%s\n", buffer);
                  } 
                  
                  fclose(book);
         return 0;
         }
    Here is the text file contents:

    Code:
    car
    dog
    truck
    pepsi
    Here is the results:

    Code:
    car
    
    
    dog
    
    
    tru
    ck
    
    pep
    si
    Press any key to continue . . .
    I'm not sure what is causing the error. Can somebody please tell me how to fix this error?

  9. #9
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Code:
    #define LINES 1024
    Code:
    while(fgets(buffer, sizeof(LINES), book)!=NULL)
    The preprocessor substitutes 1024 for LINES everywhere in your code. So, when compiling occurs that line ends up being

    Code:
    while(fgets(buffer, sizeof(1024), book)!=NULL)
    which is obviously not what you want, right? What is it you want the size of?

  10. #10
    Registered User
    Join Date
    Aug 2010
    Posts
    231
    It should be fgets(... LINES ...) or fgets(... sizeof(buffer) ...) and not fgets(... sizeof(LINES) ...).

  11. #11
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You have the words broken out onto separate rows. That part is maybe OK.

    Edit: Just saw the problem, but I've been ninja-posted!

    You want:
    Code:
     while((fgets(buffer, sizeof(buffer), book))!=NULL)
    You guys^^^ are pretty sharp for this time of the morning.
    Last edited by Adak; 11-10-2011 at 05:47 AM.

  12. #12
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    Yeah, Billy beat you to the draw. Thanks Billy.

  13. #13
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    Here is my new code:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define LINES 4096
     
    /* function prototype for percentage calculation */
    void percentage_calculation_numbers(char*, int, char*);
    
    /* function prototype to count the number of characters in a string */
    int countchar (char []);
    
    /* function prototype to find the first and last letter in the word */
    char find_letter (char* a, char* b);
    char red;
    
    /* function prototype to reverse the letters in the word */
    char* rev(char* str);
    char* reverse;
    
    /* function so I don't have to type getch all over the place */
    void MyExit(void) { system("pause"); }
      
    /* the main program */
    int numchar;
    
    int main ()
    {    
         /* declaring and initiaizing variables */
         FILE *book;
         char * pch = malloc(300);
         char alphabet1[] = "abcdefghijklmnopqrstuvwxyz";
         char buffer[LINES];
         atexit(MyExit);     
         
         /* open text file or report error */
         book = fopen("readtext.txt", "r"); 
         
         if(!book)    
         {    
              perror("Error: file readtext.txt was not found or opened");    
              return 0;    
         } 
         
         /* read from file */
                  while(fgets(buffer, sizeof(buffer), book)!=NULL) 
                  {  
                                      /* I tokenize the input string into individual words */
                                      pch = strtok (buffer, " .");
                                      
                                      /* numchar counts the numbers of characters in the pch string */
                                      numchar = countchar (pch);
                                      
                                      /* I calculate the percentage */
                                      percentage_calculation_numbers(pch, numchar, buffer);
                  } 
                  
                  fclose(book);
         return 0;
    }
     
    /* The function to find the first letter in the word */
    char find_letter (char* a, char* b)
    {
        char string = strlen(b);
        strncpy (a,b,1);
        a[1]='\0';
        return 0;
    }
      
    /* The function to reverse the characters in a string */
    char* rev(char* str)
    {
      int end= strlen(str)-1;
      int start = 0;
      
      while( start<end )
      {
        str[start] ^= str[end];
        str[end] ^=   str[start];
        str[start]^= str[end];
      
        ++start;
        --end;
      }
      
      return str;
    }
     
    /* The function to count the number of characters in a string */
     
    int countchar (char list[])
    {
        int i, count = 0;
        for (i = 0; list[i] != '\0'; i++)
            count++;
        return (count);
    }
    
    /* The function for percentage calculation */
    void percentage_calculation_numbers(char* a_pch, int a_numchar, char* a_b)
    {
        FILE *sp;
        FILE *fp;
        char *filedata = malloc(300);
        char str2[7];
        char vowels[] = "aeiouy";
        char letters[] = "bcdfghjklmnpqrstvwxz";
    	char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
        float one;
        float two;
        float three;
        float four;
        float total;
        float five;
        float six;
        float seven;
        float eight;
        float total_2;
        float percentage_1;
        float percentage_2;
        float percentage_3;
        float percentage_4;
        
        one = 0;
        two = 0;
        three = 0;
        four = 0;
        total = 0;
        five = 0;
        six = 0;
        seven = 0;
        eight = 0;
        total_2 = 0;
        percentage_1 = 0;
        percentage_2 = 0;
        percentage_3 = 0;
        percentage_4 = 0;
        
        /* open text file or report error */
       sp = fopen("readlist.txt", "r");
       fp = fopen("writelist.txt", "w");
     
        if(!sp)
        {
        perror("Error: file readlist.txt was not found or opened");
        exit(1);
        }
        if((fp = fopen("writelist.txt", "w"))==NULL) {
        printf("Cannot open file.\n");
        exit(1);
        }
        
        /* The while loop gives value to five, six, seven, eight, which is used for the percentage calculation */
      while(a_pch != NULL)
        {
    	 /* text file comparison begin */
            while(fgets(filedata, 300, sp))
            {
                if(_memicmp(a_pch, filedata, strlen(a_pch)) == 0
                    && (filedata[strlen(a_pch)] == ' '
                    || filedata[strlen(a_pch)] == '\n'))
                {
                    /* adding numchar to filedata erases the word and leaves the grammar intact */
                    printf("%s\n%s\n", a_pch, filedata+numchar+1);
                    /* write the text file comparison result to file */
                    fprintf(fp, "%s\n%s\n", a_pch, filedata+numchar+1);
                }
            }
            /* text file comparison end */
             
            /* identify the first and last letter in the word begin */
             
            red = find_letter(str2, a_pch);
            if(strpbrk(str2, letters))
            {
            one++;
            }
            if(strpbrk(str2, vowels))
            {
            two++;
            }
     
            reverse = rev(a_pch);
     
            red = find_letter(str2, a_pch);
            if(strpbrk(str2, letters))
            {
            three++;
            }
            if(strpbrk(str2, vowels))
            {
            four++;
            }
            /* identify the first and last letter in the word end */
            /* The math to see what kind of word it is start */
             
            if(total = (one && three))
            {
            five++;
            }
            else if(total = (one && four))
            {
            six++;
            }
            else if(total = (two && three))
            {
            seven++;
            }
            else if(total = (two && four))
            {
            eight++;
            }
            /* The math to see what kind of word it is end */
     
            /* Reset the pointers */
            one = 0;
            two = 0;
            three = 0;
            four = 0;
            total = 0;
            rewind(sp);
            a_pch = strtok (NULL, " ");
      }
    
      /* pch is NULL, so I find alphabet in b and pass that into pch */
      a_pch = strpbrk(a_b, alphabet);
      /* pch is backwards, so I use rev to reverse it back */
      /*printf("%s uncomment to test to see if the string is backwards", pch);*/
      reverse = rev(a_pch);
      /* count the pointers */
      total_2 = (five + six + seven + eight);
      percentage_1 = ((five)/ total_2);
      percentage_2 = ((six)/ total_2);
      percentage_3 = ((seven)/ total_2);
      percentage_4 = ((eight)/ total_2);
      printf("\nletter vowel letter %f\nletter vowel vowel %f\nvowel vowel letter %f\nvowel vowel vowel %f\n", percentage_1, percentage_2, percentage_3, percentage_4);
      /* write the pointers result to file */
      fprintf(fp, "\nletter vowel letter %f\nletter vowel vowel %f\nvowel vowel letter %f\nvowel vowel vowel %f\n", percentage_1, percentage_2, percentage_3, percentage_4);
      fclose(fp);
    }
    Here is the readlist.txt contents:

    Code:
    car n adj
    ran v
    jeremy n
    Here is the readtext.txt contents:

    Code:
    car ran 
    car ran 
    jeremy car ran
    Here is the console results:

    Code:
    car
    n adj
    
    ran
    v
    
    
    letter vowel letter 1.000000
    letter vowel vowel 0.000000
    vowel vowel letter 0.000000
    vowel vowel vowel 0.000000
    car
    n adj
    
    ran
    v
    
    
    letter vowel letter 1.000000
    letter vowel vowel 0.000000
    vowel vowel letter 0.000000
    vowel vowel vowel 0.000000
    jeremy
    n
    car
    dj
    
    ran
    dj
    
    
    letter vowel letter 0.666667
    letter vowel vowel 0.333333
    vowel vowel letter 0.000000
    vowel vowel vowel 0.000000
    Press any key to continue . . .
    And here is the writelist.txt contents after running the program:

    Code:
    jeremy
    n
    car
    dj
    
    ran
    dj
    
    
    letter vowel letter 0.666667
    letter vowel vowel 0.333333
    vowel vowel letter 0.000000
    vowel vowel vowel 0.000000
    My problem is only the last line is getting written to the text file.
    But the console is working properly now, thanks Adak.

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    If you have the console display OK, an easy way to get the output to the file OK, is to simply find and copy your printf() lines of code for the console, then make a space, and copy them right below the console's print line, but change the copied line of code to fprintf(filepointer, and the rest should all be the same.

    Do that with each of your printf() lines of code, and your file should have the same content -- IF -- you have opened the file correctly.

  15. #15
    Registered User
    Join Date
    Apr 2011
    Posts
    308
    The new code.

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #define LINES 4096
      
    /* function prototype for percentage calculation */
    void percentage_calculation_numbers(char*, int, char*);
     
    /* function prototype to count the number of characters in a string */
    int countchar (char []);
     
    /* function prototype to find the first and last letter in the word */
    char find_letter (char* a, char* b);
    char red;
     
    /* function prototype to reverse the letters in the word */
    char* rev(char* str);
    char* reverse;
     
    /* function so I don't have to type getch all over the place */
    void MyExit(void) { system("pause"); }
       
    /* the main program */
    int numchar;
     
    int main ()
    {   
         /* declaring and initiaizing variables */
         FILE *book;
         char * pch = malloc(300);
         char alphabet1[] = "abcdefghijklmnopqrstuvwxyz";
         char buffer[LINES];
         atexit(MyExit);    
          
         /* open text file or report error */
         book = fopen("readtext.txt", "r");
          
         if(!book)   
         {   
              perror("Error: file readtext.txt was not found or opened");   
              return 0;   
         }
          
         /* read from file */
                  while(fgets(buffer, sizeof(buffer), book)!=NULL)
                  { 
                                      /* I tokenize the input string into individual words */
                                      pch = strtok (buffer, " .");
                                       
                                      /* numchar counts the numbers of characters in the pch string */
                                      numchar = countchar (pch);
                                       
                                      /* I calculate the percentage */
                                      percentage_calculation_numbers(pch, numchar, buffer);
                  }
                   
                  fclose(book);
         return 0;
    }
      
    /* The function to find the first letter in the word */
    char find_letter (char* a, char* b)
    {
        char string = strlen(b);
        strncpy (a,b,1);
        a[1]='\0';
        return 0;
    }
       
    /* The function to reverse the characters in a string */
    char* rev(char* str)
    {
      int end= strlen(str)-1;
      int start = 0;
       
      while( start<end )
      {
        str[start] ^= str[end];
        str[end] ^=   str[start];
        str[start]^= str[end];
       
        ++start;
        --end;
      }
       
      return str;
    }
      
    /* The function to count the number of characters in a string */
      
    int countchar (char list[])
    {
        int i, count = 0;
        for (i = 0; list[i] != '\0'; i++)
            count++;
        return (count);
    }
     
    /* The function for percentage calculation */
    void percentage_calculation_numbers(char* a_pch, int a_numchar, char* a_b)
    {
        FILE *sp;
        FILE *fp;
        char *filedata = malloc(300);
        char str2[7];
        char vowels[] = "aeiouy";
        char letters[] = "bcdfghjklmnpqrstvwxz";
        char alphabet[] = "abcdefghijklmnopqrstuvwxyz";
        float one;
        float two;
        float three;
        float four;
        float total;
        float five;
        float six;
        float seven;
        float eight;
        float total_2;
        float percentage_1;
        float percentage_2;
        float percentage_3;
        float percentage_4;
         
        one = 0;
        two = 0;
        three = 0;
        four = 0;
        total = 0;
        five = 0;
        six = 0;
        seven = 0;
        eight = 0;
        total_2 = 0;
        percentage_1 = 0;
        percentage_2 = 0;
        percentage_3 = 0;
        percentage_4 = 0;
         
        /* open text file or report error */
       sp = fopen("readlist.txt", "r");
       fp = fopen("writelist.txt", "a+");
      
        if(!sp)
        {
        perror("Error: file readlist.txt was not found or opened");
        exit(1);
        }
        if((fp = fopen("writelist.txt", "a+"))==NULL) {
        printf("Cannot open file.\n");
        exit(1);
        }
         
        /* The while loop gives value to five, six, seven, eight, which is used for the percentage calculation */
      while(a_pch != NULL)
        {
         /* text file comparison begin */
            while(fgets(filedata, 300, sp))
            {
                if(_memicmp(a_pch, filedata, strlen(a_pch)) == 0
                    && (filedata[strlen(a_pch)] == ' '
                    || filedata[strlen(a_pch)] == '\n'))
                {
                    /* adding numchar to filedata erases the word and leaves the grammar intact */
                    printf("%s\n", filedata);
                    /* write the text file comparison result to file */
                    fprintf(fp, "%s\n", filedata);
                }
            }
            /* text file comparison end */
              
            /* identify the first and last letter in the word begin */
              
            red = find_letter(str2, a_pch);
            if(strpbrk(str2, letters))
            {
            one++;
            }
            if(strpbrk(str2, vowels))
            {
            two++;
            }
      
            reverse = rev(a_pch);
      
            red = find_letter(str2, a_pch);
            if(strpbrk(str2, letters))
            {
            three++;
            }
            if(strpbrk(str2, vowels))
            {
            four++;
            }
            /* identify the first and last letter in the word end */
            /* The math to see what kind of word it is start */
              
            if(total = (one && three))
            {
            five++;
            }
            else if(total = (one && four))
            {
            six++;
            }
            else if(total = (two && three))
            {
            seven++;
            }
            else if(total = (two && four))
            {
            eight++;
            }
            /* The math to see what kind of word it is end */
      
            /* Reset the pointers */
            one = 0;
            two = 0;
            three = 0;
            four = 0;
            total = 0;
            rewind(sp);
            a_pch = strtok (NULL, " .");
      }
     
      /* pch is NULL, so I find alphabet in b and pass that into pch */
      a_pch = strpbrk(a_b, alphabet);
      /* pch is backwards, so I use rev to reverse it back */
      /*printf("%s uncomment to test to see if the string is backwards", pch);*/
      reverse = rev(a_pch);
      /* count the pointers */
      total_2 = (five + six + seven + eight);
      percentage_1 = ((five)/ total_2);
      percentage_2 = ((six)/ total_2);
      percentage_3 = ((seven)/ total_2);
      percentage_4 = ((eight)/ total_2);
      printf("\nletter vowel letter %f\nletter vowel vowel %f\nvowel vowel letter %f\nvowel vowel vowel %f\n\n", percentage_1, percentage_2, percentage_3, percentage_4);
      /* write the pointers result to file */
      fprintf(fp, "\nletter vowel letter %f\nletter vowel vowel %f\nvowel vowel letter %f\nvowel vowel vowel %f\n\n", percentage_1, percentage_2, percentage_3, percentage_4);
      fclose(fp);
      fclose(sp);
    }
    readlist.txt

    Code:
    car n 
    ran v
    jeremy n
    readtext.txt

    Code:
    car ran.
    car ran. 
    jeremy car ran ran.
    The results after running the program are writen to writelist.txt:

    Code:
    car n 
    
    ran v
    
    
    letter vowel letter 1.000000
    letter vowel vowel 0.000000
    vowel vowel letter 0.000000
    vowel vowel vowel 0.000000
    
    car n 
    
    ran v
    
    
    letter vowel letter 1.000000
    letter vowel vowel 0.000000
    vowel vowel letter 0.000000
    vowel vowel vowel 0.000000
    
    jeremy n
    car n 
    
    ran v
    
    ran v
    
    
    letter vowel letter 0.750000
    letter vowel vowel 0.250000
    vowel vowel letter 0.000000
    vowel vowel vowel 0.000000
    Now the thing is if I feed in different characters than letters or vowels, char like '&', the program crashes. And advice on how to fix this, Adak?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Newbie question about string processing
    By prihod in forum C Programming
    Replies: 6
    Last Post: 04-15-2008, 10:14 PM
  2. processing a string troubles
    By Hoser83 in forum C Programming
    Replies: 3
    Last Post: 02-08-2006, 09:39 AM
  3. segmentation fault when processing a string
    By Nakel in forum C++ Programming
    Replies: 2
    Last Post: 04-24-2003, 04:02 PM
  4. String Processing
    By supaben34 in forum C++ Programming
    Replies: 7
    Last Post: 09-05-2002, 11:12 PM
  5. String Processing Problem
    By muffin in forum C Programming
    Replies: 0
    Last Post: 08-24-2001, 10:13 AM