Reputation: 57
The below code (which compiles fine) checks for non-alphabetical characters in a command-line input, however I feel like there's got to be a better way to write this. For example, you can see that there is no code that executes in the core if statement that checks each character in the string. Is there a way to check if one of the characters is not an alphabetical character and throw the error, rather than have the error in the else
function?
int main(int argc, string argv[]){
// terminate program if more than one key
if(argc != 2){
printf("error");
return 1;
// check to ensure key characters are alphabetical
} else {
for(int h = 0; h < strlen(argv[1]); h++){
if(isalpha(argv[1][h])){
} else {
printf("error");
return 1;
}
}
}
}
Upvotes: 0
Views: 3735
Reputation: 1971
Yes, you can invert the if-condition, which is the general solution in these cases.
int main(int argc, string argv[]){
// terminate program if more than one key
if(argc != 2){
printf("error");
return 1;
} else {
// check to ensure key characters are alphabetical
for(int h = 0; h < strlen(argv[1]); h++){
if(!isalpha(argv[1][h])){
printf("error");
return 1;
}
}
}
}
Upvotes: 1
Reputation: 6404
Strings are usually short, but calling strlen() ina for loop condition is a bad habit. It's O(N squared) because the entire string is scanned on each iteration.
Write the function like this
int allalpha(const char *str)
{
size_t i;
for(i=0;str[i];i++)
if(!isalpha(str[i]))
return 0;
return 1;
}
Then in main
if(!allalpha(argv[1]))
{
/* non all-alpha error handling code here */
}
Upvotes: 1