【发布时间】:2018-01-05 23:58:55
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void getSentence(char userSentence[]);
int breakSentence_andCompare(char userSentence[] , char compareSentence[]);
#define MAX_SENTENCE 100
int main()
{
int len = 0;
char userSentence[MAX_SENTENCE] = {'o','k',0};
char compareSentence[MAX_SENTENCE] = {'o',0};
getSentence(userSentence);
len = breakSentence_andCompare(userSentence,compareSentence);
}
/*
This function is asking the user to input info.
input:user input string array - char userSentence[].
output:none.
*/
void getSentence(char userSentence[])
{
printf("Hello And Welcome To The Palindrome Cheker Made By xXTH3 SKIRT CH4S3RXx");
printf("\nPlease Enter A Sentence: ");
fgets(userSentence,MAX_SENTENCE,stdin);
}
/*
This function takes the input of the user and input it into another string backwards.
input:user input string array - char userSentence[], backward user input string array - char compareSentence[].
output:strcmp value.
*/
int breakSentence_andCompare(char userSentence[] , char compareSentence[])
{
int i = 0;
int z = 0;
int len = 0;
int cmp = 0;
len = strlen(userSentence);
len -= 1;
for (i = len ; i >= 0 ; i--)
{
compareSentence[z] = userSentence[i];
printf("%s",compareSentence);
z++;
}
printf("\nuser: %s! compare: %s!",userSentence,compareSentence);
cmp = strcmp(userSentence,compareSentence);
printf("\n%d",&cmp);
return cmp;
}
这个程序检查输入的字符串是否是回文, 简单解释一下它是如何工作的:
- 它需要用户输入 - 字符串。
- 它采用用户字符串,输入在另一个字符串中向后。
- 它比较字符串。
我在函数中有一个非常奇怪的问题,那就是strcmp 返回值。出于某种原因,当两个字符串具有相同的字符(如 ABBA)时,strcmp 将返回其中一个的值更大。我真的很想知道问题出在哪里以及如何解决。
附言
当我搜索问题时,我认为它可能与用户输入字符串可能包含来自回车键的\n 的事实有关;这可能吗?
请理解这不是完整的代码。代码缺少输出部分。
【问题讨论】:
-
strcmp不会返回错误值,但printf("\n%d",&cmp);会。请将其更改为printf("%d\n", cmp);注意我还将换行符从开头移到结尾,类似于在书面英语中使用句号(句点)的方式。 -
printf("\n%d",&cmp);行打印的是cmp的地址,而不是它的值。 (你的编译器可能应该警告过你。) -
可能想用
userSentence[strcspn(userSentence, "\n")] = '\0';从fgets(userSentence,MAX_SENTENCE,stdin);中删除潜在的尾随'\n' -
请注意,您的标题中不必包含“初学者”。看到标题“strcmp 返回错误值”的每个人都知道两件事:1)发帖人是初学者,2)strcmp 工作正常。
-
说到 strcmp 工作得很好,我已经编程了 20 多年,并且发现我越快认为问题出在我身上,我就越早找到解决方案。暗示一个公共图书馆肯定会转移你的注意力并劝阻潜在的助手,但几乎可以肯定是错误的。
标签: c