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");
}
}
}