gpt4 book ai didi

c - strcmp 总是返回 1

转载 作者:行者123 更新时间:2023-11-30 19:20:29 25 4
gpt4 key购买 nike

以下代码中使用的变量“id”是从单独的函数获取的全局变量。它被声明并用作字符串。检查变量是一个整数。

    do{

printf("\n\n\n\n\n\n\t\tEnter the id of the account you want to transfer to: ");
fflush(stdin);
scanf("%s",&account_id);
check=strcmp(id,account_id);

printf("%d",check);//This is just a temporary check to see what strcmp is returning

if(check<0)
{
printf("\n\t\tYou cannot transfer to you own account!\n");
}

问题出在标题上。无论我输入什么值,检查始终为 1。如果我以相反的顺序比较变量(即 strcmp(account_id,id);),它确实会更改为 -1。

提前谢谢

最佳答案

虽然您没有向我们显示 idaccount_id 的值,但我预计您的问题是隐藏的换行符。

我猜:

id = "12345";
account_id = "12345\n";

\n 是您按 Enter 键时的值!

您可以在调试器中检查这一点,甚至可以使用 printf:

printf("Lengths are: %d and %d\n", strlen(id), strlen(account_id));

因此,它们比较起来并不相等。

关于c - strcmp 总是返回 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22158466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com