Thread: Questions to Structure - Beginner needs help!

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    47

    Questions to Structure - Beginner needs help!

    Hi!

    (Sorry for my bad English, but I didn’t found such a good forum in German like this!)

    I’m a beginner in C-programming and now I should write my first little program. Now I want to explain a part of my task, where I can’t find a solution on my own.
    I have to open a simple text-file and to analyze it. My program should identify different words and they have to been added to a structure like this:

    Code:
    struct list {
           char word[26];
           int quantity;
    };
    So I have to create a big algorithm with lots of while-, if- and for-loops, haven’t I?
    At this moment I have a simple working menu and I can also open a txt-file without problems. But now I haven’t any idea how I can get the different words in my structure and to print them out. Maybe I can’t remember the commands, but also Google couldn’t help me.

    I would be deeply grateful if someone could help me or give me some advises or tips!

    Kind regards
    Fresa


    PS: These are the next steps: - to count the quantity of the different words
    - to arrange them alphabetically or to arrange them to their quantity

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You're in the right forum now, and your English is fine. Welcome!

    You will want to make (above main(), the structure definition you show in your post. Then, just below that, make a global array of those structs:

    Code:
    struct list alist[50000]; //plenty large so you can hold plenty of different words
    Then, in main(), you can take in the words, using fscanf():
    Code:
    fscanf(myFilePointer, "%s ",alist[index].word); //alist[index].word is a pointer to the word
    There are several ways to handle the word counting - how many words do you expect to have, in total?

    Give that a try and read up on how to read through a file with fscanf(). Be ready to post up some code.

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    47
    Adak, thank you for your answer!

    Yes, the structure is above the main(). And this "global array of structs" I have to write INTO the main(), haven't I?
    Here is the current code. I hope the German does not anoy. There is always a little translation of the sense . Yout can tell me, if I should write it in English completely. The lower part with the headline "Analyse" (=analysis) was my first try.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    // structur
    struct Liste {
        char Wort[26];     //word
        int Anzahl;    //quantity
    };
    
    int main(void)
    { 
        char *ret, Zeile[101];
        int abfrage, nummer=0;
        FILE *datei;          //datei = data or file
    
    // Einlesen der Datei bzw. Dateiauswahl
        printf("\nAnalyse der Datei Demotext.txt\n------------------------------\n"); //the file is opened and then I test, if it was successfull or not
        datei=fopen("olo.txt","r+");
        if (datei != NULL) printf("Datei erfolgreich ge\224ffnet.\n");   //NULL = zero
        else printf("\nFEHLER: Konnte Datei nicht \224ffnen!\n");   //FEHLER = ERROR
    
        struct Liste Eintrag[800];
        fscanf(datei, "%s ", Eintrag[nummer].Wort);
    
    // Analyse
            ret=fgets(Zeile,200,datei);    //Zeile=line
    
            while(Zeile[i]!=EOF)
            {
                if(Zeile[i]=' ')              //I thought, that I have to get the position of special signs, it is incomplete and first I want to get some strings in the structure
                {
                    printf("Hallo if");   //just for testing
                }
                else
                {
                    printf("Hallo else");
                    Eintrag[nummer].Wort[26];  //entry[number].Word
                    nummer++;                       //number
                }
                i++;                  //to go from line to line
            }
        
        printf("%s", Eintrag[nummer].Wort[26]);  //output
    
        fflush(stdin);
        getchar();
        return 0;
    }
    Can you tell me the next steps? Or can you give me a hint?
    There will be about 600 words!
    Last edited by Fresa; 02-28-2012 at 04:52 AM.

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    When you have a large array, you want to either:

    *use malloc/calloc to allocate the memory from the heap part of memory

    *initiate the array in global space, ( above main() ) - again, to get memory from the heap, not a local stack memory (which is limited to 1-3 MB of memory).

    You should be OK if it's just 600 words, but remember this, just in case.

    Oh yes, I could be quite helpful with hints, but oh no, I won't rob you of that. A lot of programming is problem solving, and you have to practice it to be really good at it. Like most skills.

    I want you to sit down, with a list of 20 words, and read them off, one by one, and see how YOU want to handle this. If you didn't have a computer, how would YOU do this job?

    Post back what you decide on for your logic, and I'll help you with making it happen - just think in terms of steps:

    1) read in each word
    2) what do you want to do with them all, right after you read them in from the file? Count them now, or just enter them into the array and count them later, or a mixed approach or something different?

    If you had 500,000 words, their would be a big issue of efficiency perhaps. For 600 words, there is no issue of efficiency, but still let's not be wasteful.

    Your char can not test for an EOF - you have to have an integer for that. Fflush(stdin) is deprecated and shouldn't be used. (Overall it doesn't even work). You can flush OUTWARD streams, but not INWARD streams.

    Post up some words (10 will do), that you are trying this on, so I can if you have a problem, what is causing it easily, OK?
    Last edited by Adak; 02-28-2012 at 06:24 AM.

  5. #5
    Registered User
    Join Date
    Feb 2012
    Posts
    47
    Thanks for your detailed answer.

    There won't be more words in the future. It's just a task from school. But thank you for this important hint, I will remember of it, if I have a similar problem.
    Oh yes, I could be quite helpful with hints, but oh no, I won't rob you of that. A lot of programming is problem solving, and you have to practice it to be really good at it. Like most skills.
    I understand this, but I don't understand how I can get words form a textfile into a structure. I tried to find some tutorials or helpful sites the last days, but now I am really desperated.

    I thought of an algorithm formed in words, maybe you (or so.) can help me to get it in C.

    - read in line
    - go sign for sign through the line
    - if there is a special sign: go to the next sign
    - else: look for the next special sign and if 25 signs are getted compare this word with the other words in the structure
    - is it already in this structure, so quantity++;
    - else: add the new word
    - go to the next line

    For this algorithm I would use the following loops, but I have no idea how I can transcript it!
    Code:
    while(//- read in line)
    {
    while(//- go sign for sign through the line) {
    if(//- if there is a special sign: go to the next sign)//...
    else(//- else: look for the next special sign and if 25 signs are getted compare this word with the other words in the structure)//...
    if(//- is it already in this structure, so quantity++;)... else(//- else: add the new word)...
    }
    //- go to the next line }
    sorry, it doesn't identify the right code-type
    Last edited by Fresa; 02-28-2012 at 06:58 AM.

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    There are a few ways to "read through a line", and each of those lines, until the end of the file. The scanf() functions (including fscanf() ), return the number of items scanned and stored. So as long as fscanf() is returning > 0, then you have more data saved.

    Open your file with a FILE * variable, of course, and test that fopen() statement that it doesn't return NULL. If it returns NULL, then your file hasn't been opened, and you need to return from main(), and end the program, immediately. Print a message about the error first though. Otherwise, the user can be very surprised and not know what's going on.


    Going through the words is fairly straight forward:
    Code:
    int i = 0;
    while((fscanf(myFilePointer, "%s", lists[i].word)) > 0) {
       ++i;
    }
    Naturally, replace "myFilePointer", with the name of your file pointer variable.


    Note that this could be done char by char, but that brings in the need for more code, and less clarity results from that.

  7. #7
    Registered User
    Join Date
    Feb 2012
    Posts
    47
    I stop saying "thank you", but you can be sure, that I am always deeply grateful!!

    To open the file is no problem. Also testing if the file is correct opened does function.

    Now my code looks like this, but ist doesn't count anything. The output is "0".

    Code:
        #include <stdio.h>
        #include <string.h>
    
        // Struktur, in der die Wörter abgelegt werden:
        struct Liste { //list
            char Wort[26]; //word
            int Anzahl; //quantity
        };
    
        int main(void)
        { 
            int zeilenanzahl=3, anzahl=0, i=0, x=1; //zeilenanzahl = number  of line, later the user could say to which line the program should  analyze
            char *ret, Zeile[201]; //Zeile=line
            int nummer=0; //nummer=number
            FILE *datei; //datei=file
    
        // this is the test of opening the file
            printf("\nAnalyse der Datei Demotext.txt\n------------------------------\n");
            datei=fopen("olo.txt","r+");
            if (datei != NULL) printf("Datei erfolgreich ge\224ffnet.\n");
            else printf("\nFEHLER: Konnte Datei nicht \224ffnen!\n");
    
            struct Liste Eintrag[800]; //Liste=list, Eintrag=entry
                                                                                               //analysis      
        zeilenanzahl = zeilenanzahl + 1; //zeilenzahl = number of the line
        while(x<zeilenanzahl)
        {
            ret=fgets(Zeile,200,datei); //Zeile=line, datei=file
    
            while((fscanf(datei, "%s", Eintrag[i].Wort)) > 0) { //datei=file, Eintrag=entry, Wort=word
            
                if(Zeile[i]=' ') anzahl++; //here are the special signs, now  it should count this signs (later the words, which are seperated via  this signs), but now it count nothing
                if(Zeile[i]='.') anzahl++;
                if(Zeile[i]='!') anzahl++;
                if(Zeile[i]='?') anzahl++;
                if(Zeile[i]=',') anzahl++;
                if(Zeile[i]=';') anzahl++;
                if(Zeile[i]='-') anzahl++;
                if(Zeile[i]='_') anzahl++;
                if(Zeile[i]=':') anzahl++;
                if(Zeile[i]='\0') anzahl++;
                if(Zeile[i]='\n') anzahl++;
                if(Zeile[i]='\x0A') anzahl++;
                if(Zeile[i]='\x0D') anzahl++;
                
                else
                {
    //here it should compare the words and add them to the structure
    } i++; //to go to the next sign } x++; //to go to the next line } printf("%d", anzahl); fflush(stdin); getchar(); return 0; }
    Why does it show the code correct (with color...)?

    Okay, that's it. Where is the mistake and how can I get different words into the structure. At this moment we could ignore the comparison!
    Last edited by Fresa; 02-28-2012 at 08:10 AM.

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
                if(Zeile[i]='.') anzahl++;
                if(Zeile[i]='!') anzahl++;
                if(Zeile[i]='?') anzahl++;
                if(Zeile[i]=',') anzahl++;
                if(Zeile[i]=';') anzahl++;
                if(Zeile[i]='-') anzahl++;
                if(Zeile[i]='_') anzahl++;
                if(Zeile[i]=':') anzahl++;
                if(Zeile[i]='\0') anzahl++;
                if(Zeile[i]='\n') anzahl++;
                if(Zeile[i]='\x0A') anzahl++;
                if(Zeile[i]='\x0D') anzahl++;
    = assigns a value.
    == tests for equality


    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You need to count punctuation? Does every type of punctuation need to be counted separately, or they can be counted all together?

  10. #10
    Registered User
    Join Date
    Feb 2012
    Posts
    47
    @quzah: Thank you for your answer. It doestn't also work with "==". But I#M sorry. I don't understand, what you mean. Maybe it's difficult in cause of the translation into my mother tongue.

    @Adak: No! I don't have to count the punctuation, but I have to count the words.
    On the one hand I have to count the total quantity and on the other I have to find out the quantity of the special different words.
    example:
    Hi! My name is Fresa. The weather is great. The name of the boy is Lukas.
    total quantity: 16

    quantity of the different words:
    Hi: 1
    My: 1
    name: 2
    is: 3
    Fresa: 1
    ...

    But I thought, that I could identify the quantity of the words with the quantity of the special signs, because the words are seperatet with this signs. I know, the is the problem, that more special signs are following directly (I hope I could say it so in English).
    But I have NO IDEA!!! I need help! It was just a try to start... however...

  11. #11
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    That's different than what i thought you were doing - I thought the words were in a list:

    Edelweiss
    edelweiss
    every
    morning
    you
    greet
    me.
    etc.

    So you need to change some things. Note that punctuation doesn't need to be dealt with, because every row of text has a space between all the words, except the last word, which will have a newline (or newline/carriage return combo). So if you just count the spaces, and increment the count by one when you reach the newline, then you'll have your word count.



    This works nicely for counting the words, where I named the struct lists, and the array list[600].
    Code:
       int i = 0;
       while((fscanf(fp, "%s", list[i].word)) > 0) {
          printf("count: %d   word: %s\n",i+1,list[i].word);
          ++i; 
    
       }
    And the punctuation, even the spaces, is no longer a problem, and don't have to be messed with. Give that a run through and see what you think. Really uses fscanf() quite nicely.

    Now the only part left is the count for each individual word. How do you want to proceed with that, (in more detailed but just English, steps)?

    Work with that, I'll be off the forum for several hours.
    Last edited by Adak; 02-28-2012 at 09:49 AM.

  12. #12
    Registered User
    Join Date
    Feb 2012
    Posts
    47
    Okay, no problems
    Edelweiss... hihi

    Okay, no I have to count the words and then I have to put them into a list or structure.
    In some minutes I have visitors/companys. So, I will write later or tomorrow (an there is also the time difference )

  13. #13
    Registered User
    Join Date
    Feb 2012
    Posts
    47
    Now my program looks like this and it counts just the special signs in the line with the most special signs... strange... I will add the translation later if you want!!

    Code:
    #include <stdio.h>
    #include <string.h>
    
    // Struktur, in der die Wörter abgelegt werden:
    struct Liste {
        char Wort[26];
        int Anzahl;
    };
    
    int main(void)
    { 
        int zeilenanzahl=3, anzahl=0, i=0, x=1;
        char *ret, Zeile[201];
        int abfrage, nummer=0;
        FILE *datei;
    
    // Einlesen der Datei bzw. Dateiauswahl
        printf("\nAnalyse der Datei Demotext.txt\n------------------------------\n");
        datei=fopen("olo.txt","r+");
        if (datei != NULL) printf("Datei erfolgreich ge\224ffnet.\n");
        else printf("\nFEHLER: Konnte Datei nicht \224ffnen!\n");
    
        struct Liste Eintrag[800];
    //    fscanf(datei, "%s ", Eintrag[nummer].Wort);
                                                                                                // Analyse
        zeilenanzahl++;
        while(x<zeilenanzahl)
        {
            ret=fgets(Zeile,200,datei);
    
    //        while((fscanf(datei, "%s", Eintrag[i].Wort)) > 0)
            while (Zeile[i]!=NULL)
            {
                if( (Zeile[i]==' ') || (Zeile[i]=='.') || (Zeile[i]=='!') || (Zeile[i]=='?') || (Zeile[i]==',') || (Zeile[i]==';') || (Zeile[i]=='-') || (Zeile[i]=='_') || (Zeile[i]==':') || (Zeile[i]=='\0') || (Zeile[i]=='\n') || (Zeile[i]=='\x0A') || (Zeile[i]=='\x0D') ) anzahl++;    
    /*            else
                {
                    printf("Hallo else"); //Vergleich und hinzufügen zur Liste
                }*/
                i++;
            }
            x++;
        }
        
        printf("%d", anzahl);
    
            fflush(stdin);
            getchar();
            return 0;
        }

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Code:
    #include <stdio.h>
    
    struct alist {
       char word[26];
       int count;
    };
    
    int main(void) {
       FILE * fp;
       int i;
       struct alist list[600];
    
       
       if((fp=fopen("Edelweiss.txt","r")) == NULL) {
             printf("Error! File did not open - closing program.\n");
             return 1;
       }
       i = 0;
       while((fscanf(fp, "%s", list[i].word)) > 0) {
          printf("count: %d   word: %s\n",i+1,list[i].word);
          ++i; 
    
       }
       fclose(fp);
       printf("\n");
       return 0;
    
    
    }

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
       while((fscanf(fp, "%s", list[i].word)) > 0) {
          printf("count: %d   word: %s\n",i+1,list[i].word);
          ++i;
     
       }
    Would be better written as:
    Code:
    for( i = 0; fscanf( ... ) == 1; i++ )
        printf( ... );
    The main thing I dislike about your version is that you check > 0 when you should be checking for == 1, because all you care about is that it matches the number of scans you scan for.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Some beginner questions.
    By Kitt3n in forum C++ Programming
    Replies: 1
    Last Post: 05-15-2010, 04:18 PM
  2. A few beginner's questions
    By Megidolaon in forum C++ Programming
    Replies: 33
    Last Post: 10-24-2008, 09:21 AM
  3. Beginner's Questions
    By bjl in forum C++ Programming
    Replies: 4
    Last Post: 01-31-2008, 06:56 AM
  4. beginner questions.
    By Jaken Veina in forum C Programming
    Replies: 5
    Last Post: 03-16-2005, 09:38 PM
  5. several beginner questions...
    By Taikon in forum C Programming
    Replies: 2
    Last Post: 02-09-2005, 09:53 AM