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

  1. #31
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Quote Originally Posted by Isa-Elsino View Post
    Hey man thanks for ecerything, but I have a question.Do you know how can i sort 2 different data types of array so i dont lose the connections.Frequency of the characters and the characters.Do I need to use Struct??
    do you mean how many times each letter was picked in a random ( Frequency ) from a given set of letters?
    in other words you have an array of int = a b c ... and how many times did a random pick each one?

    this is a crude way of doing it. or unrefined method of doing that.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
    int test_alpha[3] = {'a','b','c'};
                        
    int keep_count[3] = { 0 }; 
    
    //int a = 0 , b = 0, c = 0;
    
    for (int i = 0; i < 3; i++) keep_count[i] = 0;
    
    for ( int j = 0; j < 10; j++)
    {
     
        switch ( test_alpha[  rand() % 3 + 1 ] )
        {
            case 'a':
                printf("a\n");
                keep_count[0]++; // = a += 1;
                break;
            case 'b':
                printf("b\n");
                keep_count[1]++;// = b += 1; 
                break;
            case 'c':
                printf("c\n");
                keep_count[2]++;// = c += 1;
                break;
            default:
                break;
        }
    }
    
        for ( int i = 0; i < 3; i++)
                printf("what letters %c how many times %d\n", test_alpha[i], keep_count[i]);
                
    
    return 0;
    }
    Which I am sure their is a better for efficient way of doing this, if this is what you're talking about and you want / need to under stand what it is doing better do not hesitate to use your freewill and ask.
    Last edited by userxbw; 11-05-2017 at 03:22 PM.

  2. #32
    Registered User
    Join Date
    Oct 2017
    Posts
    27
    thanks for the reply dude ,I actually managed to do that but i have hit another problem : I open a file just for reading, after that i want to open the file so I can append to it(write at the end of the file)but for some reason the program crushes
    Code:
    char  **wordarr, **wordpc;
        char sentence[1000];
        int option, library, howmany, i,number, numwords=0,count=0;
    printf("1. Dictionary build\n2. Lets play\n(pls. make a choice 1-2, 0 for exit):\n");
    scanf("%d", &option);
    
    
         //open the file
        FILE *fp;
        fp = fopen("word.txt", "r");
        if (fp == NULL) {
            fprintf(stderr, "File not found\n");
            exit(1);
        }
        //if he wants to add more words
        printf("\nDo you want to add more words?(y/n):");
        char opt;
        scanf("%s", &opt);
        if(opt == 'y'){
            printf("add the words with a space between them:\n");
    
    
            gets (sentence);
            fp = fopen("word.txt", "a");
            fprintf(fp, " %s", sentence);
            fclose(fp);
        }
    dont get confused from unused variables ,etc...

  3. #33
    Registered User
    Join Date
    Oct 2017
    Posts
    27
    Quote Originally Posted by userxbw View Post
    do you mean how many times each letter was picked in a random ( Frequency ) from a given set of letters?
    in other words you have an array of int = a b c ... and how many times did a random pick each one?

    this is a crude way of doing it. or unrefined method of doing that.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
    int test_alpha[3] = {'a','b','c'};
                        
    int keep_count[3] = { 0 }; 
    
    //int a = 0 , b = 0, c = 0;
    
    for (int i = 0; i < 3; i++) keep_count[i] = 0;
    
    for ( int j = 0; j < 10; j++)
    {
     
        switch ( test_alpha[  rand() % 3 + 1 ] )
        {
            case 'a':
                printf("a\n");
                keep_count[0]++; // = a += 1;
                break;
            case 'b':
                printf("b\n");
                keep_count[1]++;// = b += 1; 
                break;
            case 'c':
                printf("c\n");
                keep_count[2]++;// = c += 1;
                break;
            default:
                break;
        }
    }
    
        for ( int i = 0; i < 3; i++)
                printf("what letters %c how many times %d\n", test_alpha[i], keep_count[i]);
                
    
    return 0;
    }
    Which I am sure their is a better for efficient way of doing this, if this is what you're talking about and you want / need to under stand what it is doing better do not hesitate to use your freewill and ask.
    thanks for the reply dude ,I actually managed to do that but i have hit another problem : I open a file just for reading, after that i want to open the file so I can append to it(write at the end of the file)but for some reason the program crushes

    Code:
    
    
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    #define WIDTH 50
    
    
    int main()
    {
        char  **wordarr, **wordpc;
        //char sentence[1000];
        int option, library, howmany, i,number, numwords=0,count=0;
    printf("1. Dictionary build\n2. Lets play\n(pls. make a choice 1-2, 0 for exit):\n");
    scanf("%d", &option);
    while(option != 0){
    
    
         //open the file
        FILE *fp;
        fp = fopen("word.txt", "r");
        if (fp == NULL) {
            fprintf(stderr, "File not found\n");
            exit(1);
        }
        //if he wants to add more words
        /*printf("\nDo you want to add more words?(y/n):");
        char opt;
        scanf("%s", &opt);
        if(opt == 'y'){
            printf("add the words with a space between them:\n");
    
    
            gets (sentence);
            fp = fopen("word.txt", "a");
            fprintf(fp, " %s", sentence);
            fclose(fp);
        }*/
    
    
        //counts the words in the file
        int ch, letterCount = 0;
        while((ch = fgetc(fp)) != EOF){
            if(ch == ' ' || ch == '\n' ){
                count++;
            }
            else if(ch == ',' || ch == '.' || ch == '!' || ch == '?');
            else
                letterCount +=1;
        }
        printf("\nletterCount %d\ncount %d\n", letterCount, count);
    
    
    
    
        //making the array
        wordarr = (char**)malloc(sizeof(char*) * count+1);//count+1 giati afhnei sunexeia mia le3h xwris na thn metraei
        for(i = 0; i<count+1; i++){
            wordarr[i] = (char*)malloc(sizeof(char) * WIDTH);
        }
        //
        //putting the words into the array
        char buffer[10000];
        fp = fopen("word.txt", "r");
        char *tok;
        i=0;
        int d;
        while( fgets(buffer, 10000, fp) != NULL){
    
    
            int len = strlen(buffer);
    
    
             if (len > 0 && buffer[len-1] == '\n') {
                buffer[--len] = '\0';
            }
            tok = strtok(buffer, " .,!");
    
    
          while (tok != NULL) {
    
    
                int len = strlen(tok);
                for ( d = 0; d < len; d++){
                   strcpy(wordarr[i], tok);
                }
                i++;
                tok = strtok(NULL, " .,!");
            }
    
    
        }
        fclose(fp);
    
    
    
    
    
    
        int j=0;
        for (j=0; j<i; j++) {
            printf("[%s]\n", wordarr[j]);
        }
    
    
    
    
    
    
        printf("\nWrite how many letters does the word have?\n");
        scanf("%d", &number);
                //goes to the first array and searches for words with NUM characters
                //stores the words to an array
                //make a static so it can hold the position of where the word is so
                //I can copy it to the other array
        int stat_position[20];
        int position = 0,len, size=count+1, oneword = 0;
        for(i=0; i<size; i++)
        {
            len=0;
            len = strlen(wordarr[i]);
            if( len == number){
                numwords++;
                if(numwords == 1){oneword= i; }
                printf("\n%d\n", numwords);
                //only move that int array element by one if len found
                // to keep what element number the wordarr is inside of it
               // and not put the proper number element of your wordarr
                // in the same int element number
    
    
                stat_position[position]=i;
    
    
              printf("position %d word is %s\n", position,  wordarr[i]);
    
    
               position++;
            }
        }
            /**IF THE NUMBER OF WORDS EQUAL TO ONLY ONE WORD IN THE ARRAY THEN PRINTED OUT AND TERMINATE THE GAME*/
            if(numwords == 1){
                printf("\nComputer won:%s\n", wordarr[oneword]);
                exit(0);
            }
    
    
            //ALLOCATE 2DARRAY
    
    
            wordpc = (char**)malloc(sizeof(char*) * numwords);
            for(i = 0; i<numwords; i++){
                wordpc[i] = (char*)malloc(sizeof(char) * WIDTH);
            }
    
    
    
    
        printf("\n");
                // now you have your int array with the proper
            // amount of elelments holding the proper number
            // of which element number wordarr has the
            // chosen words in it by length
    
    
    
    
        for ( i = 0; i < position; i++){//MATCHING WORDS COPIED TO THE second array
            strcpy(wordpc[i], wordarr[stat_position[i]]);
        }
    
    
        //Frequency of the characters
    
    
        int freq[26];//array holding the frequency of the characters
    
    
        for(i=0; i<26; i++)
        {
            freq[i] = 0;
        }
    
    
        char alpha[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
        char str[WIDTH];
        j=0;
        int k;
    
    
        while( j < numwords){
            strcpy(str, wordpc[j]);
            //printf("%s", str);
            i=0;
            while (str[i] != '\0'){
                for( k=0; k<26; k++ ){
                    if (str[i] == alpha[k] ){
                        freq[k]++;
                    }
                }
                i++;
            }
            j++;
        }
    
    
       for (i = 0; i < 26; i++)
       {
          /** Printing only those characters
              whose count is at least 1 */
    
    
          if (freq[i] != 0)
             printf("\n%c occurs %d times in the entered string.\n", alpha[i],freq[i]);
       }
    
    
    
    
    
    
       /** Bubble Sort*/
       int swap;
       char t;
       for (i = 0 ; i < ( 26 - 1 ); i++)
      {
        for (j = 0 ; j < 26 - i - 1; j++)
        {
          if (freq[j] < freq[j+1]){
            swap = freq[j];
            freq[j] = freq[j+1];
            freq[j+1] = swap;
            t = alpha[j];
            alpha[j] = alpha[j+1];
            alpha[j+1] = t;
    
    
          }
        }
      }
    
    
      for ( i = 0 ; i < 26 ; i++ )
        printf("%d %c\n", freq[i], alpha[i]);
    
    
        //Print out the character with the biggest frequency                            //ean 3erw gw ftasei na exei akoma kai ena swsto na 8umatai to swsto kai na 3ekinaei apo kei
        i=0,j=0,k=0;
        char tempword[numwords];
        int tries=0, correct_answers=0;
        printf("Suggesting character: %c\n", alpha[i]);
        tries++;
        while( i < numwords){
            strcpy(str, wordpc[i]);
            printf("\n%s\n", str);
            while(str[j] == alpha[j]){
                //strcpy(tempword[k], alpha[j]);
                printf("\n%c", alpha[j]);
                printf("\nCorrect character.go for the next one:");
                correct_answers++;
                j++;
                tries++;
                if(tries == 6 ){
                    printf("\nComputer lost. You Won\n");
                    exit(0);
                }
            }
            printf("\n%c", alpha[j]);
            j++;
            tries++;
            if(tries == 6 ){
                printf("\nComputer lost. You Won\n");
                exit(0);
            }
            printf("\nWrong character.guess again: ");
            i++;
        }
    
    
    }
    
    
    
    
        //Deallocate the memory
        for (i=0; i<count; i++) {
            free(wordarr[i]);
            free(wordpc[i]);
        }
        free(wordarr);
        free(wordpc);
    return 0;
    }

  4. #34
    Banned
    Join Date
    Aug 2017
    Posts
    861
    here it is how you are opening it,
    Code:
     fp = fopen("word.txt", "r");
    r = read only
    w = write
    and I'd have to google the rest of them. so my guess is rw instead of just r

    go look here as well,

    2 Different types of array and I wan them to sort together.Do I need a struct?HELP

    now I am going to run your code you put in here to see what I see. But before that, as I just went back up to give it a better look, and wow,

    Dude! you need to function this thing out, and write comments that explain what you're doing inside of you code. or what your code is doing ( same thing, mostly)


    I do not have your data file word.txt to run this completely so it crashes on me. I do not remember what I called that file because I remember helping you with that part of this code.
    Last edited by userxbw; 11-05-2017 at 05:23 PM.

  5. #35
    Registered User
    Join Date
    Oct 2017
    Posts
    27
    the word.txt contains some words.Thanks i will search...

  6. #36
    Banned
    Join Date
    Aug 2017
    Posts
    861
    Quote Originally Posted by Isa-Elsino View Post
    the word.txt contains some words.Thanks i will search...
    OK I got it to run,the out put is really long so I am not going to post it. I didn't check on write to a file yet, but I am wondering what is your bubble sort for?
    printf("1. Dictionary build\n2. Lets play\n(pls. make a choice 1-2, 0 for exit):\n");
    no explanation of what each choice does. and maybe a few other points, if you want me to be asking you what your program does and what my option. that is just off the out put, let me study the code some more.
    Last edited by userxbw; 11-06-2017 at 10:49 AM.

  7. #37
    Banned
    Join Date
    Aug 2017
    Posts
    861
    I'd personally would get that to write to a file, then start refining everything, and. work on some error handling too.

    think about, would resetting my buffer be better than open read, close, open write, close, open read and append , close , open file processing vs read ( print out maybe) get input append reset buffer read print out what is now in it, get input, (write) append to file, reset buffer read print out etc.. then just closing it when you're completely done with it.
    fopen modes

    The allowed modes for fopen are as follows: r - open for reading
    w - open for writing (file need not exist)
    a - open for appending (file need not exist)
    r+ - open for reading and writing, start at beginning
    w+ - open for reading and writing (overwrite file)
    a+ - open for reading and writing (append if file exists)
    C File I/O Tutorial - Cprogramming.com
    Last edited by userxbw; 11-06-2017 at 11:27 AM.

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