c - How to make a function that iterates an isalpha function work? -
i have program compares each element in string using isalpha
. input string , calls function cycle through array , check if characters letters. if yes, prints true , false otherwise. problem can't seem make work right. return false every time.
#include <stdio.h> #include <string.h> int isalpha(char string[]); int main() { char str[100]; int bool; printf("enter string check: \n"); fgets(str, 100, stdin); bool = isalpha(str); if(bool != 0) { printf("true\n"); } else if(bool == 0) { printf("false\n"); } return 0; } int isalpha(char string[]) { int i, check, len = strlen(string); for(i = 0; < len; i++) { if(isalpha(string[i])) { check = 1; } else { check = 0; break; } } return check; }
if user enters abc
, returned string fgets
abc\n\0
. in other words, it's newline character fails isalpha
test. can fix problem subtracting 1 string length. should initialize check
variable since it's possible body of loop never run, e.g. if user presses enter without typing anything.
int i, check = 0; int len = strlen(string) - 1; for(i = 0; < len; i++)
as @shadowranger points out in comments, nothing simple in c. absolutely safe, should remove newline string shown below
int i, check = 0; string[strcspn(string, "\n")] = '\0'; int len = strlen(string); for(i = 0; < len; i++)
Comments
Post a Comment