Thread: Homework .Asap answer please.STRTOK = PROBLEM 2D ARRAY

  1. #1
    Registered User
    Join Date
    Oct 2017
    Posts
    27

    Homework .Asap answer please.STRTOK = PROBLEM 2D ARRAY

    So i have created a 2d array with malloc and I m trying to STRTOK a file and put the words in the array.I managed to do that but for some reason when i use printf ,it prints the words but it continues forever in a for loop
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    #define WIDTH 50
    
    
    int main()
    {
        /**/
        char  **wordarr, *wordpc ;
        int option=1, library, howmany, i,number, numwords=0;
    
    
        wordarr = (char**)malloc(sizeof(char*) * howmany);
        for(i = 0; i<howmany; i++){
            wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
        }
        //bazw tis le3eis apo to arxeio sto pinaka
        FILE *fp;
        fp = fopen("file.txt", "r");
        if (fp == NULL) {
            fprintf(stderr, "File not found\n");
            exit(1);
        }
        char buffer[10000];
        fgets(buffer, 10000, fp);
    
    
        char *tok;
        i=0;
        tok = strtok(buffer, " .,!");
        while (tok != NULL) {
            /*if (i >= howmany) {
                howmany *= 2;
                wordarr = (char**)realloc(wordarr, sizeof(char*) * howmany);
                for (i=howmany/2; i<howmany; i++) {
                   wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
                }
                printf("realloc\n");
            }*/
            strcpy(wordarr[(i)++], tok);
            tok = strtok(NULL, " .,!");
        }
    
    
        fclose(fp);
    
    
        for (i=0; i<howmany; i++) {
            printf("[%s]\n", wordarr[i]);
        }
    
    
    
    
        //
        for (i=0; i<howmany; i++) {
            free(wordarr[i]);
        }
        free(wordarr);

  2. #2
    Registered User
    Join Date
    Oct 2017
    Posts
    27
    So i found the problem on this . i didnt initialize the var howmany but my problem is how can i make my array big enough as are the words(numbers of the words)

  3. #3
    Banned
    Join Date
    Aug 2017
    Posts
    861
    if you look closely at your code, you are using a variable called howmany
    When and where does it get its value?
    -----------
    ok, you got it while I was posting.
    a little function then.

    Code:
    #include <stdio.h>
     
     int countStuffInFile(FILE *f){
       int count = 0;
       char ch;
       while ((ch = fgetc(f)) != EOF){
           //if (ch == '\n') // looks for end line then counts lines
           
           //if (ch == ' ') // looks for space then counts space
           
           if (ch == ' ' || ch == '\n') // does both, counts words
                count++;
       }
       return count;
    }
     
    int main(int argc, const char **argv)
    {
      
        FILE *fp;
        fp = fopen(argv[1], "r");
        if (fp == NULL) {
            fprintf(stderr, "File not found\n");
            exit(1);
        }       
        printf("how many words %d\n", countStuffInFile(fp));
        
      fclose(fp);
        return 0;
    }
    your line of thought needs to be in steps if you want to try and answer the question.
    How much space will I need for an array to shove X amount into it.
    1. open file.
    2. do a quick read of file. getting a count (words, spaces, punctuation marks, etc.. )
    of whatever it is you want to store out of that file.
    3. return that count size then go from there with calculating how to create
    a dynamically sized array.

    This is only (part of ) one idea on how to do this. keep that in mind.

    P.S. that function does not take punctuation into consideration.
    Last edited by userxbw; 10-31-2017 at 07:29 AM.

  4. #4
    Registered User
    Join Date
    Oct 2017
    Posts
    27
    thats my problem i need to know how to count the words from the file so i can make the array exactly as the number of them

  5. #5
    Banned
    Join Date
    Aug 2017
    Posts
    861
    go back and read my post again, I went and made that function after I posted then seen you were/had posting at the same time about the same thing.

  6. #6
    Registered User
    Join Date
    Oct 2017
    Posts
    27
    thanks a lot dude

  7. #7
    Registered User
    Join Date
    Oct 2017
    Posts
    27
    Quote Originally Posted by userxbw View Post
    if you look closely at your code, you are using a variable called howmany
    When and where does it get its value?
    -----------
    ok, you got it while I was posting.
    a little function then.

    Code:
    #include <stdio.h>
     
     int countStuffInFile(FILE *f){
       int count = 0;
       char ch;
       while ((ch = fgetc(f)) != EOF){
           //if (ch == '\n') // looks for end line then counts lines
           
           //if (ch == ' ') // looks for space then counts space
           
           if (ch == ' ' || ch == '\n') // does both, counts words
                count++;
       }
       return count;
    }
     
    int main(int argc, const char **argv)
    {
      
        FILE *fp;
        fp = fopen(argv[1], "r");
        if (fp == NULL) {
            fprintf(stderr, "File not found\n");
            exit(1);
        }       
        printf("how many words %d\n", countStuffInFile(fp));
        
      fclose(fp);
        return 0;
    }
    your line of thought needs to be in steps if you want to try and answer the question.
    How much space will I need for an array to shove X amount into it.
    1. open file.
    2. do a quick read of file. getting a count (words, spaces, punctuation marks, etc.. )
    of whatever it is you want to store out of that file.
    3. return that count size then go from there with calculating how to create
    a dynamically sized array.

    This is only (part of ) one idea on how to do this. keep that in mind.

    P.S. that function does not take punctuation into consideration.
    Me again sorry for bothering but i write your code into mine but the results were exactly 4 words but they were gibberish words(not the exact words)like junk

  8. #8
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Quote Originally Posted by Isa-Elsino View Post
    Me again sorry for bothering but i write your code into mine but the results were exactly 4 words but they were gibberish words(not the exact words)like junk
    that function just returns the count not the words. so I do not really know what you are talking about in how you're getting your output from your file.
    what is you code looking like?
    (I'm done, what is keeping you? )
    let me see your code.

    I'm betting you just need to reopen that file after you get your return of amount. somewhere in your code before reading it again, but after your malloc.

    still post your code.
    Last edited by userxbw; 10-31-2017 at 09:34 AM.

  9. #9
    Registered User
    Join Date
    Oct 2017
    Posts
    27
    Quote Originally Posted by userxbw View Post
    that function just returns the count not the words. so I do not really know what you are talking about in how you're getting your output from your file.
    what is you code looking like?
    (I'm done, what is keeping you? )
    let me see your code.
    Code:
    #include <stdlib.h>
    #include <string.h>
    
    
    #define WIDTH 50
    
    
    int main()
    {
        /**/
        char  **wordarr, **wordpc,ch ;
        int option=1, library, howmany, i,number, numwords=0,count=4;
    
    
    
    
        //open the file
        FILE *fp;
        fp = fopen("file.txt", "r");
        if (fp == NULL) {
            fprintf(stderr, "File not found\n");
            exit(1);
        }
        //counts the words in the file
        /*while((ch = fgetc(fp)) != EOF){
            if(ch == ' ' || ch == '\n' || ch == ',' || ch == '.'){
                count++;
            }
        }*/
        //making the array
        wordarr = (char**)malloc(sizeof(char*) * count);
        for(i = 0; i<count; i++){
            wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
        }
        //
        //putting the words into the array
        char buffer[10000];
        fgets(buffer, 10000, fp);
    
    
        char *tok;
        i=0;
        tok = strtok(buffer, " .,!");
        while (tok != NULL) {
            /*if (i >= howmany) {
                howmany *= 2;
                wordarr = (char**)realloc(wordarr, sizeof(char*) * howmany);
                for (i=howmany/2; i<howmany; i++) {
                   wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
                }
                printf("realloc\n");
            }*/
            strcpy(wordarr[(i)++], tok);
            tok = strtok(NULL, " .,!");
        }
    
    
        fclose(fp);
    
    
        for (i=0; i<count; i++) {
            printf("[%s]\n", wordarr[i]);
        }
        ////////////////
    
    
        printf("\nWrite how many letters does the word have?\n");
        scanf("%d", &number);
        int len,*temp= NULL, *tempi= NULL;
        //goes to the first array and searches for words with NUM characters
        //stores the words to an array
        for(i=0; i<count; i++){
    
    
            len = strlen(wordarr[i]);
            printf("%d", len);
            if(strlen(wordarr[i]) == number){
                printf("%d", strlen(wordarr[i]));
                numwords++;
                temp = (int*) realloc(tempi, numwords *sizeof(int));
                if(temp != NULL){
                    tempi=temp;
                    tempi[numwords-1]= i;
                }
            }
        }
        //
            wordpc = (char**)malloc(sizeof(char*) * numwords);
            for(i = 0; i<numwords; i++){
                wordpc[i] = (char*)malloc(sizeof(char) * WIDTH);
            }
        //
            /*for(i=0; i<howmany; i++){
                if(strlen(wordarr[i]) == number){
                    wordarr[tempi] = wordpc[i];
                }
            }*/
    
    
    
    
    
    
    
    
        //Deallocate the memory
        for (i=0; i<count; i++) {
            free(wordarr[i]);
            free(wordpc[i]);
        }
        free(wordarr);
        free(wordpc);

  10. #10
    Banned
    Join Date
    Aug 2017
    Posts
    861
    thats a lot of code and unused data types.
    I took this out becsue it is not needed
    Code:
        for (i=0; i<count; i++) {
            free(wordarr[i]);
            free(wordpc[i]);
        }
    just the two free statments under it are good enough. remove that in your code then try it, if still garbage, redo your test file and try it again.
    my results,
    Code:
    userx@slackwhere:~/bin
    $ ./student_toky
    [hello]
    [how]
    [are]
    [you?;
    ]
    
    Write how many letters does the word have?
    y
    5336userx@slackwhere:~/bin
    but that is only the first line in that file. are you suppose to read every line in first or just the top line?
    and it is not 5336 letters in that sentence. plus you should put an end line \n on that printf
    Last edited by userxbw; 10-31-2017 at 09:44 AM.

  11. #11
    Registered User
    Join Date
    Oct 2017
    Posts
    27
    Quote Originally Posted by userxbw View Post
    thats a lot of code and unused data types.
    I took this out becsue it is not needed
    Code:
        for (i=0; i<count; i++) {
            free(wordarr[i]);
            free(wordpc[i]);
        }
    just the two free statments under it are good enough. remove that in your code then try it, if still garbage, redo your test file and try it again.
    my results,
    Code:
    userx@slackwhere:~/bin
    $ ./student_toky
    [hello]
    [how]
    [are]
    [you?;
    ]
    
    Write how many letters does the word have?
    y
    5336userx@slackwhere:~/bin
    but that is only the first line in that file. are you suppose to read every line in first or just the top line?
    and it is not 2336 letters in that sentence. plus you should put an end line \n on that printf
    i should read all the file no matter how its written , i m going to try the code and i am going to tell you the results .thanks by the way u are great

  12. #12
    Registered User
    Join Date
    Oct 2017
    Posts
    27
    Quote Originally Posted by userxbw View Post
    thats a lot of code and unused data types.
    I took this out becsue it is not needed
    Code:
        for (i=0; i<count; i++) {
            free(wordarr[i]);
            free(wordpc[i]);
        }
    just the two free statments under it are good enough. remove that in your code then try it, if still garbage, redo your test file and try it again.
    my results,
    Code:
    userx@slackwhere:~/bin
    $ ./student_toky
    [hello]
    [how]
    [are]
    [you?;
    ]
    
    Write how many letters does the word have?
    y
    5336userx@slackwhere:~/bin
    but that is only the first line in that file. are you suppose to read every line in first or just the top line?
    and it is not 5336 letters in that sentence. plus you should put an end line \n on that printf
    u probably didnt notice that i have set the count to a 4, if i make that 0 and try it your way(counting the words doesnt work great)(i have put your code into comments)

  13. #13
    Banned
    Join Date
    Aug 2017
    Posts
    861
    you have to reopen file after count
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
     
     
    #define WIDTH 50
     
     
    int main(int argc, const char **argv)
    {
        
        char  **wordarr, **wordpc,ch ;
    
    // Commented out because they are not being used at all 
    
       // int option=1, library, howmany, i,number, numwords=0,count=4;
    
    // re declared what you are using in your program here
        int  i,number, numwords=0,count=4;
     
        //open the file
    // made it easier to just name a file / anyfile
    // on the command line to read it instead
    // it is just easier for me
    // so I can use whatever file I want
    // you do not have to do that. 
    
        char *filename = strdup(argv[1]);
    
        FILE *fp;
       
        
        fp = fopen(filename, "r");
        
        
        
        if (fp == NULL) {
            fprintf(stderr, "File not found\n");
            exit(1);
        }
    
    // get your count you want
    
        //counts the words in the file
        while((ch = fgetc(fp)) != EOF)
        {
            if(ch == ' ' || ch == '\n' || ch == ',' || ch == '.')
            { count++; }
        }
        
        //making the array
        wordarr = (char**)malloc(sizeof(char*) * count);
       
        
        for(i = 0; i<count; i++){
            wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
        }
        //
        //putting the words into the array
        char buffer[10000];
        char *tok;
        i=0;
    
        // re open file so I can read it from 
      // the start again. 
        // don't know if that is entirely legal
    // I'd have to look into it further.  but it works.
    
        fp = fopen(filename, "r");
       
      // to get it to read entire file
      // put it in a loop
      while ( fgets(buffer, 10000, fp) != NULL)
      {
        tok = strtok(buffer, " . , !");
        
        while (tok != NULL)
        {
        
            //strcpy(wordarr[(i)++], tok);
         // I just put the tok into the element
      // do it how ever you wish. both work.
            wordarr[i++] = tok;
            tok = strtok(NULL, " . , !");
        }   
        
     
    } // end outter loop
      fclose(fp);
      
       // use your i from the while loop
       // for lenght used in the array
       // so you'll just print out
       // what was put in. 
       // just make a new count var
          for (int j = 0; j < i; j++)
        {
            printf("[%s]\n", wordarr[j]);
        }
    
    // this is just crazy code to me so far. :D 
    // how is scanf reading anything?
    // it is coming up zero
    
        printf("\nWrite how many letters does the word have? y/n\n");
        scanf("%d", &number);
        printf("%d number\n", number);
        int len,*temp= NULL, *tempi= NULL;
        //goes to the first array and searches for words with NUM characters
        //stores the words to an array
        for(i=0; i<count; i++){
     
     
            len = strlen(wordarr[i]);
            printf("length %d\n", len);
            if(strlen(wordarr[i]) == number){
                // long unsinged int lu
                printf("%lu\n", strlen(wordarr[i]));
                numwords++;
                temp = (int*) realloc(tempi, numwords *sizeof(int));
                if(temp != NULL){
                    tempi=temp;
                    tempi[numwords-1]= i;
                }
            }
        }
        //
            wordpc = (char**)malloc(sizeof(char*) * numwords);
            for(i = 0; i<numwords; i++){
                wordpc[i] = (char*)malloc(sizeof(char) * WIDTH);
            }
        //
            /*for(i=0; i<howmany; i++){
                if(strlen(wordarr[i]) == number){
                    wordarr[tempi] = wordpc[i];
                }
            }*/
     
     
     
     
     
     
     
     //loop not needed
        //Deallocate the memory
       /*
        for (i=0; i<count; i++) {
            free(wordarr[i]);
            free(wordpc[i]);
        }
       */
    // just this 
        free(wordarr);
        free(wordpc);
    // me freeing my strdup
        free(filename);
        
      return 0;
    }
    Last edited by userxbw; 10-31-2017 at 10:26 AM.

  14. #14
    Banned
    Join Date
    Aug 2017
    Posts
    861
    to get total letters just keep adding len to itself
    again using i from the total count from
    your first array total
    Code:
      int len = 0, totalletter = 0;
        
        for(int g =0; g < i ; g++) 
        { 
            len = strlen(wordarr[g]);
            printf("word is %s length is %d\n",wordarr[g], len);
            totalletter += len;      
        }
        printf("total letters are %d\n", totalletter);
    test file
    Code:
    hello, how are you?
    I am fine. 
    who are YOU?
    results
    Code:
    userx@slackwhere:~/bin
    $ ./student_toky test
    [who]
    []
    [?
    ]
    [you?
    ]
    [who]
    [o]
    [re]
    [?
    ]
    [who]
    [are]
    [YOU?
    ]
    
    Write how many letters does the word have? y/n
    y
    0 number
    word is who length is 3
    word is  length is 0
    word is ?
     length is 2
    word is you?
     length is 5
    word is who length is 3
    word is o length is 1
    word is re length is 2
    word is ?
     length is 2
    word is who length is 3
    word is are length is 3
    word is YOU?
     length is 5
    total letters are 29
    counting hidden \n and whatnots you'd have to split that down to each char separately I'd think to get a perfect count. better to just do your count while getting info to put into the first array, saves a lot of coding and memory.

    MOD:
    fixed code
    Code:
      //counts the words in the file
        // and how many letters used
        // skips noted puncuation marks
        int letterCount = 0, count = 0;
        while((ch = fgetc(fp)) != EOF)
        {
            if(ch == ' ' || ch == '\n' )
            {
                
                count++;
                printf("ch= %c\ncount %d\n", ch, count);
            }
            else if (ch == ',' || ch == '.' || ch == '!' || ch == '?')
            ; // dont count it
            else
                letterCount += 1;
            
        }
        printf("letterCount %d\ncount %d\n", letterCount, count);
    do not forget to reopen file
    Last edited by userxbw; 10-31-2017 at 11:25 AM.

  15. #15
    Registered User
    Join Date
    May 2012
    Location
    Arizona, USA
    Posts
    953
    Quote Originally Posted by userxbw View Post
    Code:
       char ch;
       while ((ch = fgetc(f)) != EOF){
    Please don't do this. The fgetc() and getchar() functions return an "int". "EOF" is some unspecified negative value, and some systems have an unsigned "char" type (C standards allow "char" to be either signed or unsigned), which means it will never be able to hold the value of "EOF".

    On systems where "char" is signed and can hold the value of "EOF", if a byte with that value happens to occur in a binary file you're reading, you'll stop reading the file prematurely. Imagine you're reading a file that has a byte with the value 0xFF. getchar() returns the value 0xFF (255), but if you cast it to a (signed) "char", that value gets converted to -1, which is the same value as EOF on many systems. The file doesn't actually end there, but your program mistakenly believes it does.

    As you can see, whether your system uses signed or unsigned char, you're going to have problems if you stuff the return value of fgetc() or getchar() into a char rather than an int.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. problem with homework on array(2)
    By mr_plopper in forum C Programming
    Replies: 8
    Last Post: 10-14-2015, 10:28 AM
  2. problem with homework on array
    By Kenny Dearing in forum C Programming
    Replies: 4
    Last Post: 10-12-2015, 12:04 PM
  3. Help with comparing answer to math problem and user's answer
    By Jake Garbelotti in forum C Programming
    Replies: 6
    Last Post: 07-20-2012, 10:12 PM
  4. need homework help asap with if statement
    By automagp68 in forum C Programming
    Replies: 26
    Last Post: 01-27-2012, 02:19 PM

Tags for this Thread