#include <stdio.h>
#include <string.h>
void processString(char *str, int *totVowels, int *totDigits);
int main()
{
char str[50], *p;
int totVowels, totDigits;
printf("Enter the string: \n");
fgets(str, 80, stdin);
if (p = strchr(str, '\n')) *p = '\0';
processString(str, &totVowels, &totDigits);
printf("Total vowels = %d\n", totVowels);
printf("Total digits = %d\n", totDigits);
return 0;
}
void processString(char *str, int *totVowels, int *totDigits)
{
int i, j;
char tester[11] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
*totDigits = 0;
*totVowels = 0;
for (i = 0; i < strlen(str); i )
{
if (isdigit(str[i]))
{
*totDigits = 1;
}
else if(isalpha(str[i]))
{
for (j = 0; j < 11; j )
{
if (strcmp(str[i], tester[j]) == 0)
{
*totVowels =1;
}
}
}
}
}
My code is trying to calculate the number of times a number and vowel appeared in a string.
My string compare is trying to check for vowels but the program ends when it reaches the strcmp
line. Why is that happening? Is my syntax wrong?
P.S. I'm only allowed to edit in the processString
function, the rest are all given.
CodePudding user response:
Your problems lies is the code if (strcmp(str[i], tester[j]) == 0)
. Because you are referencing single-dimensional arrays, the dereference comes out to be a single character. Essentially you are comparing two chars
, and chars
can be compared for equality like ints
. And strcmp
is designed for comparing strings, not single chars
. That is why it segfaults (segfaults are due to invalid pointer dereferences. In this case it tried to dereference a non-pointer. A definite no-no.)
The fix would be to replace that line with: if (str[i] == tester[j])
.