I have to count the amount of times "e" and "E" occur in a string using a function, everything is working except for the counting of the e's
I believe my professor is looking for me to use strcmp but I cannot figure out how to use that correctly so I went a different route and that is not working either.
sorry added main code
#include <stdio.h> #include <stdlib.h> #include <string.h> #define ARRLEN 30 #define CODELEN 5 //functions int numOfE(char [], int); int main(void) { //Variables char codeWord [CODELEN] ; char inputString [ARRLEN] ; int length = 0 ; int numbOfEs = 0 ; //Name printf("Grace Rombach\n") ; //Get codeword printf("Please enter the code: ") ; gets(codeWord) ; while (strcmp(codeWord, " ") !=0) { printf("Please enter the code: ") ; gets(codeWord) ; } //Collect string printf("Please enter a string less than 30 characters: ") ; gets(inputString) ; length = strlen(inputString); while (length >= 30) { printf("Please enter a string less than 30 characters: ") ; gets(inputString) ; length = strlen(inputString); } numbOfEs = numOfE(inputString,length) ; printf("%s -%d",inputString,numbOfEs) ;
}
int numOfE (char inputString[], int length) { int eCounter = 0 ; int i = 0 ; char charE = "E" ; char chare = "e" ; for (i = 0; i < length; i ) { if(inputString[i]== charE || inputString[i]== chare) { eCounter ; } } return (eCounter); }
CodePudding user response:
Should be (using more normal coding conventions too)
int numOfE (char *inputString)
{
int eCounter = 0;
char charE = 'E';
char chare = 'e'
for (int i = 0; i < strlen(inputString); i )
{
if(inputString[i] == charE || inputString[i] == chare)
{
eCounter ;
}
}
return eCounter;
}
the reason it failed was because yo used "E" instead of 'e'
Although I would do
if(inputString[i] == 'E' || inputString[i] == 'e')
and leave out charE and chare since it makes the intent clearer
CodePudding user response:
As @pm100 mentioned the problem was that you need to use single quotes for characters instead of double quotes.
Here's a full example where I use a rather general version of the character counter function.
#include <stdio.h>
#include <ctype.h> // to use the "tolower()" function
#include <string.h> // to use the "strlen()" function
int countChar(char inputString[], char c)
{
int counter = 0;
int length = strlen(inputString);
int i = 0;
for (i = 0; i < length; i ) {
if (tolower(inputString[i]) == tolower(c)) counter ;
}
return counter;
}
int main () {
char str[] = "hamEde";
char c = 'e';
printf("The (case insensitive) count of '%c's in \"%s\" = %d\n", c, str, countChar(str, c));
}
Output: The (case insensitive) count of 'e's in "hamEde" = 2