My program should keep prompting the user to enter the correct format of string if there are duplicates of letters or the string contains non-alphabetic characters.
However, it does not work correctly. It seems that it cannot find out whether characters are alphabetic or not, while works fine to distinguish duplicate letters and keep prompting the user to enter string one more time.
Also, I've tried to do it without isalpha()
function. Instead of that, I checked for condition of uppercase character belonging into the range between 'A'
and 'Z'
. Even in that case the program did not work right.
Here is the function and test that I've tried:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int check(char key[]) {
int flag = 1;
int counts[strlen(key)];
int i, j;
for (i = 0; i < strlen(key); i++) {
counts[i] = 0;
}
for (i = 0; i < strlen(key); i++) {
for (j = 0; j < strlen(key); j++) {
if (toupper(key[i]) == toupper(key[j])) {
counts[i]++;
}
}
}
for (i = 0; i < strlen(key); i++) {
if (counts[i] > 1 || isalpha(key[i]) == 0) {
/* if I remove
isalpha related condition it works fine
to find only duplicate letters
and keep asking user to input
another string */
flag = 0;
}
}
return flag;
}
int main() {
int size = 20;
char str[size];
printf("Enter a string w/o duplicate letters and non-alphabetic characters: ");
fgets(str, size, stdin);
//test 1. str = "hello" -> prompt to enter str again since there 2 'l's (this part works well but only to find duplicate letters)
//test 2. str = "helo12" -> prompt to enter str again since there are non-alphabetic characters
//test 3. str = "naruto" -> program keeps working further
while (check(str) != 1) {
printf("Illegal word! \nEnter again: ");
fgets(str, size, stdin);
}
}