Reputation: 13
I'm trying to write a program to deal with user input in C. I have to ensure the program accept the input by user like taking "y", "yep", "yeah" as "yes" in my program for later use (i.e. need to use strcmp(xx,"yes") == 0). I have handled the mixed case character.
So how can I write a function to summerize "y", "yeah", "yep" and make them equal to "yes" after all??
if ((strcmp(letter , "y") == 0) || ......)
return "yes";
.......
Plus, if the program asks users to enter a question for some purposes, is it possible to add a question mark (?) for users if users forget to add one?
Upvotes: 0
Views: 102
Reputation: 5297
There is a function named strncasecmp
which is not present on all Systems (I'm a Linux User), because is not a standard function:
int strncasecmp(const char *s1, const char *s2, size_t n);
The function looks like this if is not present on your System:
int strncasecmp(char *s1, char *s2, size_t n){
if (n == 0){
return 0;
}
while (n-- != 0 && tolower(*s1) == tolower(*s2)){
if (n == 0 || *s1 == '\0' || *s2 == '\0'){
break;
}
s1++;
s2++;
}
return tolower(*(unsigned char *) s1) - tolower(*(unsigned char *) s2);
}
Which you can use it like this:
#include <stdio.h>
#include <strings.h>
int main(void){
char *user_input = "yes";
char *ch = "Y";
if (strncasecmp(user_input, ch, 1) == 0){
printf("True\n");
}else{
printf("False\n");
}
return 0;
}
As you can see there is no problem with case sensitive. The strncasecmp
function is found in strings.h
and not in string.h
is it possible to add a question mark (?) for users if users forget to add one?
Yes, you can. The following piece of code is a way to help you to understand how to do it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
char *question = "What is your Question";
size_t length = strlen(question);
char *addQuestion = malloc(length + 2);
memcpy(addQuestion,question,length + 1);
printf("Before\n%s\n",addQuestion);
strcat(addQuestion, "?");
printf("\n");
printf("After\n%s\n",addQuestion);
free(addQuestion);
return 0;
}
Output:
Before
What is your Question
After
What is your Question?
Upvotes: 0
Reputation: 355
Just compare the first letter with 'y'. For example, if you save the user input in a variable called user_input
:
if ((user_input[0] == 'y') || ...)
And as for your second question, you can add that option, for example (it validates the input length before adding the "?", thanks to Vane for the correction):
if ((input_length > 0) && (user_input[input_length-1] != '?')) {
strcat(user_input, "?");
}
Upvotes: 1