Wortlängenhistogramm



  • Hallo,
    ich soll ein Programm schreiben, das einen Text von der Tastatur einliest und dann die Länge der in dem Text enthaltenen Wörter auf dem Bildschirm ausgibt.
    Das Ganze soll so aussehen :

    Text = ? Dies ist ein Beispieltext

    3 ##
    4 #
    12 #

    Wer weiß wie das geht ?



  • Hier mal meine Version von der Kernighan Ritchi Aufgabe 1_14.
    Die zählt zwar nur die verschiedenen Buchstaben, allerding gibts dafür ein vertikales Histogramm.
    Ist allerdings in C 😞

    /*
    *
    *   Solutions to the exericises of "The C Programming Language" book
    *   by Brian W. Kernighan and Dennis M. Ritchie.
    *
    *   Exercise 1-14
    *
    */
    
    #include <stdio.h>
    
    #define NUMBER_OF_CHARS 26 /* 'a' - 'z' */
    #define IN 1
    #define OUT 0
    
    int main()
    {
        int c;
        int state;
        int hist[NUMBER_OF_CHARS];
        int max;
    
        for(c=0; c<NUMBER_OF_CHARS; c++) {
            hist[c] = 0;
        }
    
        while((c=getchar()) != EOF) {
            if(c >= 'a' && c <= 'z') {
                hist[c-'a']++;
            }
        }
    
        /* vertical histogram */
        max = hist[0];
        for(c=1; c<NUMBER_OF_CHARS; c++) {
            if(hist[c] > max) {
                max = hist[c];
            }
        }
    
        state = IN;
        while(state == IN) {
            printf("\t");
            state = OUT;
            for(c=0; c<NUMBER_OF_CHARS; c++) {
                if(hist[c] > 0) {
                    state = IN;
                    if(hist[c] == max) {
                        hist[c]--;
                        printf(" - ");
                    } else {
                        printf("   ");
                    }
                } else {
                    printf("   ");
                }
            }
            max--;
            printf("\n");
        }
        printf("freq:\t");
        for(c='a'; c<='z'; c++) {
            printf(" %c ", c);
        }
    
    return 0;
    }
    

    Vielleicht hilfts Dir.



  • #include <iostream> 
    #include <vector>
    #include <algorithm>
    #include <string>
    
    void PrintResult(const std::string Word)
    {
    	std::cout<<"[Length: "<< Word.length() <<"] "<< Word <<std::endl;
    };
    
    int main ()
    { 
    	std::vector<std::string> TextBuffer;
    	std::string Word;
    
    	while(Word != ">END<") 
    	{
    		std::cout<<"Zum Auswerten >END< eingeben"<<std::endl;
    
    		std::cin>> Word;
    
    		TextBuffer.push_back(Word);
    	}
    
    	std::for_each(TextBuffer.begin(), TextBuffer.end(), PrintResult);
    
    	return 0;
    }
    

Anmelden zum Antworten