I'm currently working on a program that will compare a set of input strings to a user input. The only condition is I'm not allowed to use built-in string operations; I must code them all from scratch.
The input strings is an array of strings like so:
char *input_strings[] = {
"Hello", "What is your name?", "How are you?", "Bye"
};
What I currently have is a bunch of functions:
1) uppercheck, which checks if a value is uppercase or not:
int uppercheck(int c){
return (c >= 'A' && c <= 'Z');
}
2) lowercase, which converts a value to lowercase:
int lowercase(int c){
if (uppercheck(c)){
c + 0x20;
}
else{
c;
}
}
3) compstr, which compares two lowercase strings:
int result;
int compstr(char str1[], char str2[]){
for(int i = 0; str1[i]; i++){
if (lowercase(str1[i]) == lowercase(str2[i])){
result = 1;
}
else{
result = 0;
}
}
return result;
}
The latter part of my code checks if the user string is equal to each entry in the input_strings array, like so:
char input[100]; // user input string
while (1) // infinite loop
{
//Get the input string
printf("> ");
fgets(input, 100, stdin);
// comparing strings:
//3 base input conditions:
if (compstr(input_strings[0], input) == 1)
{
printf("Hello\n");
}
else if (compstr(input_strings[1], input) == 1)
{
printf("My name is Name\n");
}
else if (compstr(input_strings[2], input) == 1)
{
printf("I am fine\n");
}
//exit condition:
else if (compstr(input_strings[3], input) == 1)
{
printf("Bye\n");
break;
}
//invalid input:
else
{
printf("I do not understand\n");
}
}
return 0;
My problem is that the program will output "Hello" for ANY input, even when there's no input at all. I thought that the compare function would make sure the two strings are identical, but it doesn't seem to work and I'm not sure how to approach it from here. Sorry if I overdid the code but I figured I'd add as much info as possible. Any help would be heavily appreciated!
<ctype.h>? They're not string functions, so you nominally should be able to do so. If so, use them:isupperandtolower()seem to be what you want — though you could speed things up by noting thattolower()only changes upper-case letters; anything else is passed through unchanged, so you don't need to test for upper-ness — just convert everything withtolower()and compare the results.