0

the issue i have is that the code keeps adding letters after the 'for' code, if i write "ni pratar bra latin" it will become "nipratarbralatintin" with an exta "tin"

    int ret1;
    int size = 0;
    int i = 0;
    char ch[100];


    printf("WELCOME USER\n");
    printf("ENTER A SENTENCE OR A WORD FOR THE PROGRAM TO START.\n");
    printf("THE PROGRAM WILL CHECK IF YOUR SENTENCE / WORD IS A PALENDROME");
    printf("\n");
    scanf(" %[^\n]s", &ch);

Removes spaces aka the part im having issues with

    for (i = 0, size = 0; i < strlen(ch); i++) {
        ch[i - size] = ch[i];
        if (ch[i] == ' ')
            size++;
    }
    ch[i] = '\0';

    ret1 = isPalindrome(ch);
    int quit;

    if (ret1 == 1)
        // 1 means string is palendrome
        printf("\nYOUR SENTENCE/WORD: %s IS A PALENDROME", ch);
    else if (ret1 == 0)
        // 0 means string is not palendrome
        printf("\nYOUR SENTENCE/WORD: %s IS NOT A PALENDROME", ch);
Federico Baù
  • 6,013
  • 5
  • 30
  • 38
Anna
  • 1

1 Answers1

1

The line

    ch[i] = '\0';

is wrong. The line is meaningless because \0 will already be there on ch[i] because it is after exiting the loop with the condition i < strlen(ch).

The line should be

   ch[i - size] = '\0';

to maintain consistency with the line inside the loop ch[i - size] = ch[i];.

Also the line

    scanf(" %[^\n]s", &ch);

is wrong because char(*)[100] is passed where char* is expected and undefined behavior is invoked.

It should be

    scanf(" %[^\n]s", ch);

without the extra &.

This version with checking is better:

   if (scanf(" %[^\n]s", &ch) != 1) {
       fputs("read error\n", stderr);
       /* exit program (return from main(), using exit(), etc. */
   }
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • With a width limit, `scanf(" %[^\n]s"` has same problems as [gets](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). There is no reason for the `"s"` in `" %[^\n]s"`. Consider `" %99[^\n]"`. – chux - Reinstate Monica Jan 27 '21 at 15:14