program issues

This is a discussion on program issues within the C Programming forums, part of the General Programming Boards category; Hello I am trying to create a program for analyzing user input words and have come up against a problem ...

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

    program issues

    Hello

    I am trying to create a program for analyzing user input words and have come up against a problem with the results returned.

    The program starts by asking the user for a character string but goes a little wrong from there. When case 3 is selected first it runs fine and returns good results for all cases, but when case 3 is selected after any other case it returns zeros for all values. All of the individual cases do work when used independantly. I am a complete newbie at this so may have missed something really silly, and I apologise if the code below looks weird as I wasn't sure how to submit it.

    Any help will be greatly appreciated, thanks.
    Code:
     
    #include<stdio.h>
    #include<string.h>
    #include<ctype.h>
    int main(void)
    {
        char string[256], b[256], c;
        int i = 0, found = 1, function = 0, characters = 0, vow = 0, cons = 0, spaces = 0, dig = 0, other = 0;
    //
    //Variables declared above and menu options are below.
    //
        printf("Enter a string of words:");
        gets(string);
        while (function != 5)
        {
            printf("1. Find word count\n");
            printf("2. Find character count\n");
            printf("3. Find the number of vowels and consonants\n");
            printf("4. Find if the string is a palindrome\n");
            printf("5. Quit\n\n");
            scanf("%d", &function);
            switch (function)
            {
    //
    //The options chosen above now select the operations below
    //
            case 1:
                for (i = 0; i < strlen(string); i++)
                    if (string[i] == ' ')
                        found++;
                printf("The word count is %d\n\n", found);
                break;
    //
    //The above operation counts the number of words in the string by counting spaces
    //
            case 2:
                for (i = 0; i < strlen(string); i++)
                    if (isalpha(string[i]))
                        characters++;
                printf("The character count is %d\n\n", characters);
                break;
    //
    //The above operation counts the number of alphabet characters only
    //
            case 3:
                while ((c = tolower(string[i++])) != '\0')
                {
                    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
                        ++vow;
                    else if (c >= 'a' && c <= 'z')
                        ++cons;
                    else if (c >= '0' && c <= '9')
                        ++dig;
                    else if (c == ' ')
                    {
                        ++spaces;
                        while (string[i] == ' ' || string[i] == '\t')
                        {
                            i++;
                            spaces++;
                        }
                    }
                    else
                        other++;
                }
                printf("The total number of vowels is %d\n", vow);
                printf("The total number of consonants is %d\n", cons);
                printf("The total number of numeric characters is %d\n", dig);
                printf("The total number of special characters is %d\n", other);
                printf("The total number of line spaces is %d\n\n", spaces);
                break;
    //
    //The above operation breaks down the string into its component parts
    //after converting all text to lower case
    //
            case 4:
                strcpy(b, string);
                strrev(b);
                if (strcmp(string, b) == 0)
                    printf("The string is a palindrome\n\n");
                else
                    printf("The string is not a palindrome\n\n");
                break;
    //
    //The above operation tests the string to see if it reversable
    //
            case 5:
                break;
            default:
                printf("Error please enter only between 1 and 5\n");
            }
        }
    }
    
    Attached Files Attached Files

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Your program should be divided into functions (if you know how).
    You should use fgets instead of gets, because fgets is safer (allowing you to specify a maximum number of chars to read so that your array doesn't overflow).
    You should return 0 from main.

    You should init your counting variables at the beginning of each case. What happens if you choose case 1 twice in a row?

    A similar error is causing your case 3 problem. You're not initializing i at the top of case 3.

  3. #3
    Registered User
    Join Date
    Feb 2012
    Posts
    15
    Thank you for such a quick reply. If i choose any of the cases more than once it adds the result to the previous so there may be a bigger problem than i first thought, Should i move all of the appropriate variables within each case ie i, c, vow cons within case 3 etc

  4. #4
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    You don't actually need to "move" the variables there, i.e., you can still leave their declarations at the top of main. Just initialize the requisite variables at the beginning of each case.

  5. #5
    Registered User
    Join Date
    Feb 2012
    Posts
    15
    My apologies very new to this, how do I initialize them do you have an example

  6. #6
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Case 1 uses the variable found and also i. i is being initialized in the init section of the for loop. So you need to init found like this:
    Code:
            case 1:
                found = 0;
                for (i = 0; i < strlen(string); i++)
                    if (string[i] == ' ')
                        found++;
                printf("The word count is %d\n\n", found);
                break;
    Do the same for the other cases, initing whatever vars they use.

  7. #7
    Registered User
    Join Date
    Feb 2012
    Posts
    15
    That works perfectly, cant thank you enough.

  8. #8
    Registered User
    Join Date
    Feb 2012
    Posts
    15
    Would it be ok to ask how to loop this program so that the user doesnt have to exit each time to enter a new word i have tried both adding an extra case and a do while loop but nether seem to want to go back through the program. I have posted the currently working program again so the changes from before are visible.
    Thanks

    Code:
    #include<stdio.h>
    #include<string.h>
    #include<ctype.h>
    int main(void)
    {
    	char string[256], b[256], c;
    	int  i = 0, found = 1, function = 0, characters = 0, vow = 0, cons = 0, spaces = 0, dig = 0, other = 0;
    //
    //Variables declared above and menu options are below.
    //
    	printf("Enter a string of words:\n\n");
    	gets(string);
    	while (function != 5)
    	{
    		printf("1. Find word count\n");
    		printf("2. Find character count\n");
    		printf("3. Find the number of vowels and consonants\n");
    		printf("4. Find if the string is a palindrome\n");
    		printf("5. Quit\n\n");
    		scanf("%d", &function);
    		switch (function)
    		{
    //
    //The options chosen above now select the operations below
    //
    		case 1:
    			found = 1;
    			i = 0;
    			for (i = 0; i < strlen(string); i++)
    				if (string[i] == ' ')
    					found++;
    			printf("The word count is %d\n\n", found);
    			break;
    //
    //The above operation counts the number of words in the string by counting spaces
    //
    		case 2:
    			characters = 0;
    			i = 0;
    			for (i = 0; i < strlen(string); i++)
    				if (isalpha(string[i]))
    					characters++;
    			printf("The character count is %d\n\n", characters);
    			break;
    //
    //The above operation counts the number of alphabet characters only
    //
    		case 3:
    			vow = 0;
    			cons = 0;
    			dig = 0;
    			spaces = 0;
    			other = 0;
    			i = 0;
    			while ((c = tolower(string[i++])) != '\0')
    			{
    				if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
    					++vow;
    				else if (c >= 'a' && c <= 'z')
    					++cons;
    				else if (c >= '0' && c <= '9')
    					++dig;
    				else if (c == ' ')
    				{
    					++spaces;
    					while (string[i] == ' ' || string[i] == '\t')
    					{
    						i++;
    						spaces++;
    					}
    				}
    				else
    					other++;
    			}
    			printf("The total number of vowels is %d\n", vow);
    			printf("The total number of consonants is %d\n", cons);
    			printf("The total number of numeric characters is %d\n", dig);
    			printf("The total number of special characters is %d\n", other);
    			printf("The total number of line spaces is %d\n\n", spaces);
    			break;
    //
    //The above operation breaks down the string into its component parts
    //after converting all text to lower case
    //
    		case 4:
    			strcpy(b, string);
    			strrev(b);
    			if (strcmp(string, b) == 0)
    				printf("The string is a palindrome\n\n");
    			else
    				printf("The string is not a palindrome\n\n");
    			break;
    //
    //The above operation tests the string to see if it reversable
    //
    		case 5:
    			break;
    		default:
    			printf("Error please enter only between 1 and 5\n");
    		}
    	}
    	return 0;
    }
    Attached Files Attached Files

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I haven't run this, but it should be quite close. You were on the right track.

    Code:
    #include<stdio.h>
    #include<string.h>
    #include<ctype.h>
    int main(void)
    {
    	char string[256], b[256], c;
    	int  i = 0, found = 1, function = 0, characters = 0, vow = 0, cons = 0, spaces = 0, dig = 0, other = 0;
    //
    //Variables declared above and menu options are below.
    //
       while (function != 5)
       {    
    
    	 printf("Enter a string of words:\n\n");
    	 gets(string);
    
    	 printf("1. Find word count\n");
    	 printf("2. Find character count\n");
    	 printf("3. Find the number of vowels and consonants\n");
    	 printf("4. Find if the string is a palindrome\n");
    	 printf("5. Quit\n\n");
    	 scanf("%d", &function);
    	 getchar(); //remove the newline
             switch (function)
    	 {
    //
    //The options chosen above now select the operations below
    //
    		case 1:
    			found = 1;
    			i = 0;
    			for (i = 0; i < strlen(string); i++)
    				if (string[i] == ' ')
    					found++;
    			printf("The word count is %d\n\n", found);
    			break;
    //
    //The above operation counts the number of words in the string by counting spaces
    //
    		case 2:
    			characters = 0;
    			i = 0;
    			for (i = 0; i < strlen(string); i++)
    				if (isalpha(string[i]))
    					characters++;
    			printf("The character count is %d\n\n", characters);
    			break;
    //
    //The above operation counts the number of alphabet characters only
    //
    		case 3:
    			vow = 0;
    			cons = 0;
    			dig = 0;
    			spaces = 0;
    			other = 0;
    			i = 0;
    			while ((c = tolower(string[i++])) != '\0')
    			{
    				if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
    					++vow;
    				else if (c >= 'a' && c <= 'z')
    					++cons;
    				else if (c >= '0' && c <= '9')
    					++dig;
    				else if (c == ' ')
    				{
    					++spaces;
    					while (string[i] == ' ' || string[i] == '\t')
    					{
    						i++;
    						spaces++;
    					}
    				}
    				else
    					other++;
    			}
    			printf("The total number of vowels is %d\n", vow);
    			printf("The total number of consonants is %d\n", cons);
    			printf("The total number of numeric characters is %d\n", dig);
    			printf("The total number of special characters is %d\n", other);
    			printf("The total number of line spaces is %d\n\n", spaces);
    			break;
    //
    //The above operation breaks down the string into its component parts
    //after converting all text to lower case
    //
    		case 4:
    			strcpy(b, string);
    			strrev(b);
    			if (strcmp(string, b) == 0)
    				printf("The string is a palindrome\n\n");
    			else
    				printf("The string is not a palindrome\n\n");
    			break;
    //
    //The above operation tests the string to see if it reversable
    //
    		case 5:
    			break;
    		default:
    			printf("Error please enter only between 1 and 5\n");
    		}
    	}
    	return 0;
    }
    If you have user input for a number, but they goof and enter a letter, it will crash your program (try it and see), unless you make a provision to handle the single char, and remove it from the input stream. The getchar() I added above, will do that.

    How are you spelling reversible (ahem)? Looks like a well done program.
    Last edited by Adak; 02-23-2012 at 04:51 AM.

  10. #10
    Registered User
    Join Date
    Feb 2012
    Posts
    15
    I did wonder why it went funny when a character was entered, thanks. I have made the change but it now asks for the word to be entered between each option is there a way to get it to hold on to the initial input so that all options can be used before a new word is entered

  11. #11
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    You can also "eat" a char out by adding a space before the % sign in the scanf() format string: scanf(" %d", &numberYouWant).

    You need two loops. The outer loop (which I added), is needed to allow multiple strings to be entered. The inner loop (which you had before), is needed to allow multiple analysis of the string that was entered.

    The values that you have at the top (except function), need to be reset inside the outer loop, and before the inner loop begins. That allows every string to have a clean set of values, before the analysis begins on it, and not have any values from the previous string's analysis.

    Give that a try.

  12. #12
    Registered User
    Join Date
    Feb 2012
    Posts
    15
    Ok that kind of makes sense will give it a go and let you know, thanks for your help.

  13. #13
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Quote Originally Posted by Adak View Post
    You can also "eat" a char by adding a space before the % sign in the scanf() format string: scanf(" %d", &numberYouWant).
    Even without the space, the %d will skip whitespace before reading the number.
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  14. #14
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by oogabooga View Post
    Even without the space, the %d will skip whitespace before reading the number.
    Correct, but in a loop, the skip doesn't work the way you might think it would.

    Run this.

    Code:
    #include <stdio.h>
    
    int main(void) {
       int number=0;
       while(number > -1) {
          printf("Enter an integer (but for this test, enter a letter instead): ");
          scanf("%d",&number);
          //getchar();
          printf("The number you entered was: %d\n",number);
       }
       printf("\n");
       return 0;
    }
    Now either add a getchar() inside the loop (preferably after the scanf(), or add a space before the % sign in the scanf() format string, and again, enter a letter instead of a number.

    Big difference.

    BTW Oogabooga, you've been giving some great advice on the forum, including John here.
    Last edited by Adak; 02-23-2012 at 10:10 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Circle Program Issues
    By hannah_banana10 in forum C++ Programming
    Replies: 9
    Last Post: 04-07-2010, 04:54 PM
  2. First Program Issues
    By sfr1 in forum C++ Programming
    Replies: 4
    Last Post: 07-29-2009, 07:43 PM
  3. Issues with Anagram Program
    By toadkiwi in forum C Programming
    Replies: 2
    Last Post: 04-16-2008, 10:20 PM
  4. issues with program need help
    By clipsit in forum C Programming
    Replies: 6
    Last Post: 04-03-2008, 10:24 AM
  5. Well having issues with this other program here...
    By Junior89 in forum C++ Programming
    Replies: 2
    Last Post: 05-06-2007, 11:39 PM

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