can someone double check and maybe improve my code

This is a discussion on can someone double check and maybe improve my code within the C Programming forums, part of the General Programming Boards category; This program is supposed to count the vowels ('a','e','i','o',and 'u') in a string that the user writes. Counters are to ...

  1. #1
    Registered User
    Join Date
    Mar 2004
    Posts
    78

    can someone double check and maybe improve my code

    This program is supposed to count the vowels ('a','e','i','o',and 'u') in a string that the user writes. Counters are to be used separately for each vowel. Can someone check to see if I wrote it correctly and does what it's supposed to do. If you can improve it, without getting too complicated, please do so. Any comments are also strongly encouraged. Thank you........
    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <ctype.h>
    
    int main()
    {
      char message[81];   /* enough storage for a complete line   */
      
      int index,a,e,i,o,u,z;
      index=0,a=0,e=0,i=0,o=0,u=0,z=0;
    
      printf("Please enter a sentence:");
      gets(message);
    
     for (index=0; message[index];index++)
    	message[index]=toupper(message[index]);
    
      for (index=0;message[index] !='\0';index++)
      {
    	  if (message[index]=='A')
    		  a++;
    	  else if (message[index]=='E')
    		  e++;
    	  else if (message[index]=='I')
    		  i++;
    	  else if (message[index]=='O')
    		  o++;
    	  else if (message[index]=='U')
    		  u++;
    	   
      }
       printf("\nThe following vowles are in the sentence you just typed:\n\n");
    
      printf("Vowel a:  %d\n", a);
      printf("Vowel e:  %d\n", e);
      printf("Vowel i:  %d\n", i);
      printf("Vowel o:  %d\n", o);
      printf("Vowel u:  %d\n", u);
    
      getch();
    
      return 0;
    }

  2. #2
    Registered User
    Join Date
    Aug 2003
    Posts
    470
    The logic looks ok, however gets shouldn't be used. I also wouldn't use o as a var since you're likely to confuse it with 0. Probably best to name your vars "numO" or something similar.

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    Are you writing in C or C++?
    Because this is a C program posted on the C++ board

    > gets(message);
    Read the FAQ

    This is how you read a line in C
    fgets( message, sizeof message, stdin );


    > for (index=0; message[index];index++)
    > for (index=0;message[index] !='\0';index++)
    Be consistent in your loop conditions.

    > getch();
    This is a non-standard function.
    Ways of pausing at the end of the program are also discussed in the FAQ
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  4. #4
    Registered User
    Join Date
    Mar 2004
    Posts
    78
    I am using C. Thanks for the FAQ link. I know I have a lot to learn and it doesn't help when when teachers don't insist on using the fgets() instead of the gets() function. Do you know why this is? Like why not introduce the class both functions and then lean more toward the fgets() function. I'll tweak my code with your advice. Thanks again!! Tommy

  5. #5
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    > Do you know why this is?
    I wish I knew.

    Mostly, it seems to because they're not actually programmers who have written programs any larger than the ones in the book they're reading.

    Or the book they're reading was "written" by Herb Schildt
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  6. #6
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    >>I am using C.
    Then I'll move this to the C forum.

    I was bored, so here's my version of the program for you to ponder over.

    Code:
     #include <stdio.h>
     #include <ctype.h>
     
     #define NUM_VOWELS 5
     #define VOWELS "AEIOU"
     
     int main()
     {
       char  buf[BUFSIZ];
       int   VowelsCount[NUM_VOWELS] = {0};
       int   i, j;
       
       printf("Please enter a sentence:");
       fflush(stdout);
       
       if (fgets(buf, sizeof(buf), stdin))
       {
         for (i = 0; buf[i] != '\0'; i++)
         {
           for (j = 0; j < NUM_VOWELS; j++)
           {
             if (toupper(buf[i]) == VOWELS[j])
             {
               VowelsCount[j]++;
               break;
             }
           }
         }
       }
       
       printf("\nThe following vowles are in the sentence you just typed:\n\n");
     
       for (i = 0; i < NUM_VOWELS; i++)
       {
         printf ("Vowel %c:  %d\n", VOWELS[i], VowelsCount[i]);
       }
     
       return 0;
     }
     
     /*
     
     Output
     
     Please enter a sentence:The sly fox jumped over someone, I think!
     
     The following vowels are in the sentence you just typed:
     
     Vowel A:  0
     Vowel E:  5
     Vowel I:  2
     Vowel O:  4
     Vowel U:  1
     
     */
    >>Counters are to be used separately for each vowel.
    Oh well, mine uses an array
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  7. #7
    ~viaxd() viaxd's Avatar
    Join Date
    Aug 2003
    Posts
    246
    that's cool, Hammer, i didn't know you can do that in C:

    Code:
    #define VOWELS "AEIOU"
    ...
    VOWELS[j]

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >i didn't know you can do that in C:
    A string literal is just a pointer, and the subscript operator is syntactic sugar wrapped around basic pointer arithmetic. The fact that the string literal is hidden behind the preprocessor should make no difference because once preprocessing is done the compiler sees this:
    Code:
    "AEIOU"[j]
    Some people are surprised that this works at first, but it's really very intuitive and often useful.
    My best code is written with the delete key.

  9. #9
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    Code:
    j[VOWELS]
    also works
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  10. #10
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >also works
    For some definitions of "works". Sure, it's legal and correct syntactically and semantically, but I wouldn't expect to see it anywhere except code trying to throw beginners.

    Are you trying to confuse beginners Salem? You meanie.
    My best code is written with the delete key.

  11. #11
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    472
    >>index=0,a=0,e=0,i=0,o=0,u=0,z=0

    you can simplify this with the below command:
    index=a=e=i=o=u=z=0;

    not much difference, i suppose.

  12. #12
    /*enjoy*/
    Join Date
    Apr 2004
    Posts
    159
    salut
    je vous conseille tous d'abord de voir un livre d'algorithmique pour ameliorer vos competences
    2emme pour ce programme je vous conseille d'utuliser (enum) c'est a dir d'enumere les lettre choisies puis de faire une boucle ou une fonction avec (switch)
    si vous ne connaissez pas le syntaxe le voila
    switch(variable)
    {
    case(variable):{anything to do}
    .
    .
    .
    .
    .
    case(n):...
    defaul:{anything to do}
    }
    si vous voulez que je fait cet exercice a votre palce demandez le et je n'hesiterai pas a te donner un coup de main
    mon e-mail est ziro@voila.fr
    bonne chance

  13. #13
    C Programmer Stack Overflow's Avatar
    Join Date
    Apr 2004
    Posts
    477

    Post

    Hello,

    I think I might have a simple way of executing this. What I will do is create an integer array called "vowelIndex[]", where vowelIndex[0] is 'a', vowelIndex[1] is 'e', and etc...

    Also I'll use strpbrk() in this example. It's a nice function, and the first time I get to use it in an example. I will also write another function called "checkVowel()" to increment the correct index per vowel found.

    After that I'll do a simple display of how many times it was found and so forth. Also, but using strpbrk(), it allows you to start the vowel process when the first one is found. Just like strstr(), strpbrk() just lets you search for a char. I am also going to use fgets() with stdin, to get the inputted data.

    I'll post the example, and explain more after:

    Code:
    void checkVowel(int index[], int c) {
    	switch ( c ) {
    	case 'a':
    	case 'A:
    		index[0] += 1;
    	break;
    	case 'e':
    	case 'E':
    		index[1] += 1;
    	break;
    	case 'i':
    	case 'I':
    		index[2] += 1;
    	break;
    	case 'o':
    	case 'O':
    		index[3] += 1;
    	break;
    	case 'u':
    	case 'U':
    		index[4] += 1;
    	break;
    	}
    }
    
    int main() {
    	char buffer[81], *pch;
    	char vowels[] = "aeiou";
    	int vowelIndex[5] = {0};
    
    	printf("Enter a sentence: ");
    	fgets(buffer, sizeof(buffer), stdin);
    
    	// Start at first vowel
    	pch = strpbrk(buffer, vowels);
    
    	// While the string isnt at 0
    	while (pch != NULL) {
    		// Add to the vowel index
    		checkVowel(vowelIndex, *pch);
    		// Search again
    		pch = strpbrk(pch+1, vowels);
    	}
    	printf("\n");
    
    	// Display
    	printf("\'a\' found %i times\n", vowelIndex[0]);
    	printf("\'e\' found %i times\n", vowelIndex[1]);
    	printf("\'i\' found %i times\n", vowelIndex[2]);
    	printf("\'o\' found %i times\n", vowelIndex[3]);
    	printf("\'u\' found %i times\n", vowelIndex[4]);
    
    	return 0;
    }
    Code 1.1: Using strpbrk() to search vowels

    Well, that wasn't to bad at all. Now of course the full listing of vowelIndex[] is:

    vowelIndex[0] is 'a'
    vowelIndex[1] is 'e'
    vowelIndex[2] is 'i'
    vowelIndex[3] is 'o'
    vowelIndex[4] is 'u'
    Now what I do is firstly, create a few variables. A buffer, a char[] for vowels, *pch for searching through buffer, and vowelIndex to remember how many were found.

    Firstly, skipping printf(), I use fgets() instead of gets(). I've heard that gets() is very unstable and does not allow you to set the maximum bytes allowing buffer overflow to occur. Also, stdin is the information inputted, else stdout, outputted. Once I recieve the data, I flush the stream, so none of the data just floats out there.

    Then, I use the strpbrk() function. This allows me to scan a string for specified characters. I then set *pch to the first vowel found, if any. Then, once a vowel was found, send the data to my checkVowel() then to increment which vowel was found using += 1 also using the switch statement.

    Lastly, I use a while loop to check if pch does not equal NULL or '\0' or the null terminator. Of course then using my checkVowel(), then once I'm all done, do the search again, this time doing pch+1, or saying where we left off.

    I hope this has helped, and/or may help you in the near future. If I do have any inappropriate code, or something might be misleading, please let me know.


    Hope this helps,
    Stack Overflow
    Last edited by Stack Overflow; 04-19-2004 at 12:03 PM.
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  14. #14
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    472
    heres my version....similair to hammers...
    Code:
    #include <string.h>
    #include <stdio.h>
    #include <ctype.h>
    
    int main()
    {
        char in[BUFSIZ], *p, *f, *v="aeiouz";
        int vowels[6] = {0}, i;
        
        printf("Enter a string...\n>>");
        fflush(stdout);
        
        fgets(in,sizeof(in),stdin);
        
        for (p=in;*p != '\0';p++)
            if ( ( f = strchr(v,tolower(*p)) ) != NULL)
                vowels[f-v]++;
    
        printf("Your sentance contained...\n");
        for (i=0;i<6;i++)
            printf("%cs: %d\n",v[i],vowels[i]);
            
        return 0;
    }

  15. #15
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    472
    Code:
    int checkVowel(int index[], int c) {
    	if( c == 'a' )
    		index[0] += 1;
    	else if( c == 'e' )
    		index[1] += 1;
    	else if( c == 'i' )
    		index[2] += 1;
    	else if( c == 'o' )
    		index[3] += 1;
    	else if( c == 'u' )
    		index[4] += 1;
    
    	return true;
    }
    why dont you just use a switch statement?
    you could even include different cases, and then not require toupper/tolower..like so:

    Code:
    switch (letter) {
      case 'E':
      case 'e':
        dostuff;
        break;
      case 'A':
      case 'a':
        dostuff;
        break;
    ...
      case 'U':
      case 'u':
        dostuff;
        break;
      default:
        break;
    }
    just my 2 cents..

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

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