#include <stdio.h>
#include <ctype.h>
int main() {
char str[100];
char out[] = "exit";
do {
printf("Enter a string: ");
scanf("%s", str);
// some if else statement here
{ while (toupper(str[3]) != toupper(out[3]));
I put the index 3 because if I put the index 0 there, the code will terminate if the entered string starts with letter e. I tried the while loop but it does not work for me. Also I want to print a prompt message that says "detected terminate keyword" after entering the word "exit" and then terminates the loop.
You will also notice the toupper()
function. I used it there because I want my loop to be case insensitive, so regarless of lowercase or uppercase or combination of both, the loop should terminate when the word "exit" is entered.
CodePudding user response:
toupper(str[3]) != toupper(out[3])
will compare the upper case 4th letter of str
and out
, so the loop will iterate till str[3]
is 'T'
. You want to use strcasecmp(str, out)
instead. Remember to #include <strings.h>
.
CodePudding user response:
char *removeLastChar(char *str, char ch)
{
size_t len;
if(str)
{
len = strlen(str);
if(str[len - 1] == ch) str[len -1] = 0;
}
return str;
}
char *strlwr(char *str)
{
char *wrk = str;
if(str)
{
while(*wrk)
{
*wrk = tolower((unsigned char)*wrk);
wrk ;
}
}
return str;
}
int main(void)
{
char str[100];
const char *out = "exit";
int x = 0;
do
{
printf("Enter a string: ");
if(!fgets(str, sizeof(str), stdin)) break;
removeLastChar(str, '\n');
printf("You entered: \"%s\"\n:", str);
} while (strcmp(strlwr(str), out));
}
CodePudding user response:
There are multiple problems:
it is confusing for a function
isPalindrome()
to return0
for true.to avoid undefined behavior on negative
char
values, achar
argument totoupper
should be cast as(unsigned char)
.the test for the
exit
keyword is incorrect. You exit if the fourth letter is at
or aT
. You should usestrcasecmp
to test for theexit
word.scanf("%s", str)
has potential undefined behavior if the user enters a word with more than 99 bytes. Usescanf("