首页 > 解决方案 > strcmp() 函数未提供预期输出

问题描述

我是 C 新手。该程序是反转一个字符串,检查它是否是回文并打印反转的字符串。尽管即使在输出中(输出在代码下方),反转的字符串与原始字符串相同,但 strcmp() 函数给出了错误的输出。

#include<stdio.h>
#include<string.h>
int main()
{
    int n;
    scanf("%d",&n);
    char ch[n];
    scanf("%s",&ch);
    n=strlen(ch);
    char temp[n];
    int k=0;
    for(int i=n-1;i>=0;i--)
    {
        temp[k]=ch[i];
        k+=1;
    }
    int l=strcmp(ch,temp);
    printf("%d\n",l);
    if(l==0)
    printf("PALINDROME\n");
    else
    printf("NOT PALINDROME\n");
    for(int i=0;i<n;i++)
    printf("%c",temp[i]);
    return 0;
}

输出 1

6
nitin
1
NOT PALINDROME
nitin

输出 2

100
nitin
1
NOT PALINDROME
►p@PduV⌡ uVP8a■╚   ■ ☺Σ┼uT╠└a ╠a■ä☺a■╨@↕α@↕αè9Å¥uVP½uZFuVP╬a■░nitin

标签: cfor-loopc-stringspalindromestrcmp

解决方案


对于初学者而不是

 scanf("%s",&ch);
            ^^^

你必须写

 scanf("%s",ch);

该数组temp不包含字符串。所以这个电话strcmp

int l=strcmp(ch,temp);

调用未定义的行为。

您需要在 for 循环之后附加temp带有终止零字符的数组,例如'\0'

temp[k] = '\0';

为此,您需要像这样声明数组

n=strlen(ch);
char temp[n + 1];

推荐阅读