开发者

why are the strings not equal?

#include "usefunc.h"
#define MY_SIZE 256

int inpArr(char tmp[], int size) {
    size = -1;
    while(1) {
        size++;
        if((tmp[size] = getchar()) == '\n') break;
    }
    return size;
}

void revString(char tmp[], int size, char new[]) {
    int i, j;
    for (i = size, j = 0; i >= 0; i--, j++) new[j] = tmp[i];
}

void copy_forw(char tmp[], int size, char new[], int offset) {
    int i, j;
    for (i = offset, j = 0; i <= size; i++, j++) new[j] = tmp[i];
}

void copy_back(char tmp[], int size, char new[], int offset) {
    int i, j;
    for (i = size-offset, j = size; i > -1; i--, j--) new[j] = tmp[i];
}

void cut(char tmp[], int size, char new[]) {

}

int main () {
    char tmp[MY_SIZE] = {0x0}, rev[MY_SIZE] = {0x0}, new[MY_SIZE] = {0x0}, some[MY_SIZE-1];
    int size = inpArr(tmp, size);
    revString(tmp, size, rev);
    copy_forw(rev, size, new, 1); copy_back(tmp, size, some, 1);
    printf("|%s|\n|%s|\n", some, new);
    int is_palindrome = StringEqual(new, some);
    printf("%d\n", is_palindrome);
}

StringEqual i开发者_StackOverflow社区s pretty much a function that just compares a char array character by character.

If I input the string yay it should be a palindrome, but doesn't appear to be. Why is this?


Your problem is with the line that goes:

if((tmp[size] = getchar()) == '\n') break;

This line will always assign the character the user inputs into the array, even when the user inputs the \n character to indicate that they are done providing input. So for example, when you enter "yay" and then a newline to indicate that you are done, your array looks like:

{'y', 'a', 'y', '\n'}

and the reverse of that array is:

{'\n', 'y', 'a', 'y'}

...which will obviously fail a palindrome check. I would suggest revising your code as follows:

int inpArr(char tmp[], int size) {
    size = -1;
    while(1) {
        size++;
        if((tmp[size] = getchar()) == '\n') break;
    }
    tmp[size] = '\0';  //replace the newline with a null terminator
    return size;
}

void revString(char tmp[], int size, char new[]) {
    int i, j;
    for (i = size - 1, j = 0; i >= 0; i--, j++) new[j] = tmp[i];
    new[size] = '\0';  //place a null terminator at the end of the reversed string
}


Look at line:

if((tmp[size] = getchar()) == '\n') break;

'\n' is always present at the end of the string. That's your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜