Like Tree6Likes

converting from a const char to a char.

This is a discussion on converting from a const char to a char. within the C Programming forums, part of the General Programming Boards category; You still NEED to remove the extra semi colon I hinted to you about yesterday. Code: while(r < count); Last ...

  1. #16
    Registered User
    Join Date
    May 2009
    Posts
    2,478
    You still NEED to remove the extra semi colon I hinted to you about yesterday.

    Code:
    while(r < count);
    Last hint for tonite

    I think is really should be set to 0 instead of 1.
    Code:
    int r = 1;  // might have to be 1 instead of 0
    Last edited by stahta01; 04-14-2013 at 06:25 PM.
    Dude22 likes this.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the Universe is winning." Rick Cook

  2. #17
    Registered User
    Join Date
    May 2009
    Posts
    2,478
    In case, I decide to help more posting the missing code needed to get the program to run.

    Cut-down version of dictionary.h found on-line somewhere.
    Code:
    /****************************************************************************
     * dictionary.h
     *
     * Computer Science 50
     * Problem Set 6
     *
     * Declares a dictionary's functionality.
     ***************************************************************************/
    
    #ifndef DICTIONARY_H
    #define DICTIONARY_H
    
    #include <stdbool.h>
    
    
    // maximum length for a word
    // (e.g., pneumonoultramicroscopicsilicovolcanoconiosis)
    #define LENGTH 45
    
    
    /*
     * Returns true if word is in dictionary else false.
     */
    
    bool check(const char *word);
    
    
    /*
     * Loads dictionary into memory.  Returns true if successful else false.
     */
    
    bool load(const char *dictionary);
    
    
    /*
     * Returns number of words in dictionary if loaded else 0 if not yet loaded.
     */
    
    unsigned int size(void);
    
    
    /*
     * Unloads dictionary from memory.  Returns true if successful else false.
     */
    
    bool unload(void);
    
    
    #endif // DICTIONARY_H
    Cut-down version of test code without timing; my system is missing resource header.
    Code:
    #include <ctype.h>
    #include <stdio.h>
    #include <sys/time.h>
    
    #include "dictionary.h"
    
    // default dictionary
    #define DICTIONARY "/home/cs50/pset6/dictionaries/large"
    
    int
    main(int argc, char *argv[])
    {
        // check for correct number of args
        if (argc != 2 && argc != 3)
        {
            printf("Usage: speller [dictionary] text\n");
            return 1;
        }
    
        // determine dictionary to use
        char *dictionary = (argc == 3) ? argv[1] : DICTIONARY;
    
        // load dictionary
        bool loaded = load(dictionary);
    
        // abort if dictionary not loaded
        if (!loaded)
        {
            printf("Could not load %s.\n", dictionary);
            return 2;
        }
    
        // try to open text
        char *text = (argc == 3) ? argv[2] : argv[1];
        FILE *fp = fopen(text, "r");
        if (fp == NULL)
        {
            printf("Could not open %s.\n", text);
            unload();
            return 3;
        }
    
        // prepare to report misspellings
        printf("\nMISSPELLED WORDS\n\n");
    
        // prepare to spell-check
        int index = 0, misspellings = 0, words = 0;
        char word[LENGTH+1];
    
        // spell-check each word in text
        for (int c = fgetc(fp); c != EOF; c = fgetc(fp))
        {
            // allow only alphabetical characters and apostrophes
            if (isalpha(c) || (c == '\'' && index > 0))
            {
                // append character to word
                word[index] = c;
                index++;
    
    
                // ignore alphabetical strings too long to be words
                if (index > LENGTH)
                {
                    // consume remainder of alphabetical string
                    while ((c = fgetc(fp)) != EOF && isalpha(c));
    
    
                    // prepare for new word
                    index = 0;
                }
            }
    
            // ignore words with numbers (like MS Word can)
            else if (isdigit(c))
            {
                // consume remainder of alphanumeric string
                while ((c = fgetc(fp)) != EOF && isalnum(c));
    
    
                // prepare for new word
                index = 0;
            }
    
            // we must have found a whole word
            else if (index > 0)
            {
                // terminate current word
                word[index] = '\0';
    
                // update counter
                words++;
    
                // check word's spelling
                bool misspelled = !check(word);
    
                // print word if misspelled
                if (misspelled)
                {
                    printf("%s\n", word);
                    misspellings++;
                }
    
                // prepare for next word
                index = 0;
            }
        }
    
        // check whether there was an error
        if (ferror(fp))
        {
            fclose(fp);
            printf("Error reading %s.\n", text);
            unload();
            return 4;
        }
    
        // close text
        fclose(fp);
    
        // determine dictionary's size
        unsigned int n = size();
    
        // unload dictionary
        bool unloaded = unload();
    
        // abort if dictionary not unloaded
        if (!unloaded)
        {
            printf("Could not unload %s.\n", dictionary);
            return 5;
        }
    
        // report benchmarks
        printf("\nWORDS MISSPELLED:     %d\n", misspellings);
        printf("WORDS IN DICTIONARY:  %d\n", n);
        printf("WORDS IN TEXT:        %d\n", words);
    
        // that's all folks
        return 0;
    }
    Dude22 likes this.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the Universe is winning." Rick Cook

  3. #18
    Noobin to the max
    Join Date
    Mar 2013
    Posts
    73

    Weird

    weird, It is now going through every word, although it is checking each word 2 times.... Also it says EVERY word is not spelled correctly, even though some of them are. I believe the second error is because the new line character is not being removed. But the first error (every word twice) has me stumped... Here is my code:

    Code:
    #include <stdio.h>
    #include "dictionary.h"
    #include <string.h>
    #include <stdlib.h>
    
    
    #define MAXWORDS 26
    #define DLENGTH 46
    
    
    int count = 0;
    
    
    char **result = NULL;
    
    
    /**
     * Returns true if word is in dictionary else false.
     */
    bool check(const char* word)
    {
        int r = 0;
        char temp[51];
        strncpy(temp,word,51);
        char *new_word = malloc(strlen(word)+1);
        
        if (new_word) 
        {
        strcpy(new_word,word);
        printf("%s\n", new_word);
        }
        
        while(r < count)
        {
            if(strcmp(new_word, result[r]) != 0)
            {
                r++;
            }
            else if(strcmp(new_word, result[r]) == 0)
            {
                return true;
            }
        }
        
        return false;
    }
    
    
    
    
    /**
     * Loads dictionary into memory.  Returns true if successful else false.
     */
    bool load(const char* dictionary)
    {
    
    
    int ch = 0;
    
    
    
    
    FILE *f = fopen("test.txt", "r");
    
    
    while ((ch = fgetc(f)) != EOF)
        {
            if (ch == '\n')
                count++;
        }
    
    
    rewind(f);
    
    
    result = malloc( count * sizeof(*result) );
    
    
    //size_t total_size = 0;
    //size_t num_bytes = 0;
    
    
    char buf[0x1000];
    
    
    int i = 0;
    
    
    while ( fgets( buf, sizeof(buf), f) != NULL ) {
    
    
        result[i] = malloc( strlen(buf) + 1 );
        strcpy( result[i], buf );
        
        i++;
    
    
        //result = &p;
        //memcpy(result + total_size, buf, num_bytes);
        //total_size += num_bytes;
    }
    
    
        //printf("%s\n",result);
    
    
    //fclose(f);
    
    
    
    
    return true;
      
    }
    
    
    
    
    
    
    /**
     * Returns number of words in dictionary if loaded else 0 if not yet loaded.
     */
    unsigned int size(void)
    {
    if (count != 0)
    {
        return count;
    }
    else
    {
       return 0;
    }
    }
    
    
    /**
     * Unloads dictionary from memory.  Returns true if successful else false.
     */
    bool unload(void)
    {
    return true;
    }

    And this is what it prints out when it runs:

    MISSPELLED WORDS


    like
    like
    test
    test
    abce
    abce
    and
    and
    then
    then
    the
    the
    they
    they
    there
    there
    where
    where
    example
    example
    thirty
    thirty
    jar
    jar
    this
    this
    you
    you
    do
    do
    skis
    skis
    a
    a
    aaaaaaaaaaaaaaaaaaaaaaa
    aaaaaaaaaaaaaaaaaaaaaaa


    WORDS MISSPELLED: 18
    WORDS IN DICTIONARY: 642940
    WORDS IN TEXT: 18
    TIME IN load: 0.15
    TIME IN check: 0.06
    TIME IN size: 0.00
    TIME IN unload: 0.00
    TIME IN TOTAL: 0.21


    I really can't figure out why it is checking every word 2 times, so any advice on that would be great!

    Also, as for it thinking everything is misspelled... Like I said, I think it is because of the newline character. I know I have been given advice on removing that already, but I just can't wrap my head around what has been said, so more advice on this would be great!

    Also, If you think the first error is being caused by something else, please feel free to let me know!
    There is always one more bug...

    Remember, don't name you php arrays "hit"

  4. #19
    Registered User
    Join Date
    May 2009
    Posts
    2,478
    FYI: You are never going to be a good or average C Programmer; if you could not figure out how to cut and paste from the link I gave you. If you are planning on a career in programming I suggest changing your focus to something else.

    Tim S.

    Code:
    char *p;                                         /* Added Line */
    
    while ( fgets( buf, sizeof(buf), f) != NULL ) {
     
            if ((p = strchr(buf, '\n')) != NULL) /* Added Line */
             *p = '\0';                                /* Added Line */
    
        result[i] = malloc( strlen(buf) + 1 );
        strcpy( result[i], buf );
         
        i++;
     
     
        //result = &p;
        //memcpy(result + total_size, buf, num_bytes);
        //total_size += num_bytes;
    }
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the Universe is winning." Rick Cook

  5. #20
    Noobin to the max
    Join Date
    Mar 2013
    Posts
    73
    Quote Originally Posted by stahta01 View Post
    FYI: You are never going to be a good or average C Programmer; if you could not figure out how to cut and paste from the link I gave you. If you are planning on a career in programming I suggest changing your focus to something else.

    Tim S.
    Don't worry, my career choice, leans towards electrical/mechanical engineering. I am in this course, because I want to simply understand basic programming.

    As a wise man once said: Programmers make no money. Engineers, make a lot of money. Engineers, that also understand programming, make a friggin lot of money.


    Anyways, thanks, for that, the program now works! There is just one small detail, that is the unload function... What should I unload to avoid memory leaks???

    Thanks,
    Josh
    There is always one more bug...

    Remember, don't name you php arrays "hit"

  6. #21
    Registered User
    Join Date
    May 2009
    Posts
    2,478
    Quote Originally Posted by Dude22 View Post

    Anyways, thanks, for that, the program now works! There is just one small detail, that is the unload function... What should I unload to avoid memory leaks???

    Thanks,
    Josh
    Normally any alloc call needs a matching free call.

    Tim S.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the Universe is winning." Rick Cook

  7. #22
    Registered User
    Join Date
    Apr 2013
    Posts
    1,255
    Try this change:

    Code:
    int i = 0; 
      while ( fgets( buf, sizeof(buf), f) != NULL ) {
          result[i] = malloc(strlen(buf));
          buf[strlen[buf]-1] = 0; /* remove newline */
          strcpy( result[i], buf ); 
          i++; 
      }
    
    Note - if this is windows / dos and you read a text file in binary mode, there are 2 characters at the end of each line, 0xd, 0xa).

Page 2 of 2 FirstFirst 12
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting int to const char* ?
    By Wiretron in forum C++ Programming
    Replies: 7
    Last Post: 11-12-2007, 01:49 PM
  2. Converting an std::string to a const char *
    By Shamino in forum C++ Programming
    Replies: 21
    Last Post: 01-24-2006, 03:03 PM
  3. Converting from type char to const char*
    By Leeman_s in forum C++ Programming
    Replies: 1
    Last Post: 05-21-2003, 09:51 PM
  4. Assigning Const Char*s, Char*s, and Char[]s to wach other
    By Inquirer in forum Linux Programming
    Replies: 1
    Last Post: 04-29-2003, 10:52 PM
  5. Converting const char to char array
    By HomerJ in forum C++ Programming
    Replies: 4
    Last Post: 04-30-2002, 03:21 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21