简体   繁体   English

麻烦C else,如果和scanf

[英]Trouble with C else, if and scanf

I am new to C and I'm making my first "decent" program. 我是C语言的新手,正在制作我的第一个“不错的”程序。 I am facing trouble with my code. 我的代码遇到了麻烦。

char username[] = "root";
char usernametry[10];

scanf("%s",usernametry);

if (usernametry == username)
{
    printf("Welcome ROOT user\n");
}
else
{
    printf("Try again\n");
}

Whenever I execute my program, everything works; 每当我执行我的程序时,一切正常。 however, when I try to log in and type root as the username, it returns Try again . 但是,当我尝试登录并输入root作为用户名时,它将返回Try again Can someone suggest why this is happening? 有人可以建议为什么会这样吗? I am very new to C so I apologize for my lack of C knowledge. 我对C非常陌生,因此我对缺乏C知识深表歉意。

usernametry and username are arrays of type char . usernametryusernamechar类型的数组。 When you do usernametry == username , you are not comparing if two strings are equal, you are comparing the memory address of the first char in usernametry with the memory address of the first char in username . 当你做usernametry == username ,你是不是比较两个字符串是否相等,你是比较第一的内存地址charusernametry与第一的内存地址charusername In order to compare if two strings are equal, you should use strcmp . 为了比较两个字符串是否相等,应使用strcmp Also, consider replacing %s in your scanf with %9s so that usernametry will never exceed 9 char s (which would have been a buffer overflow, as the 10th char needs to be '\\0' , the null character, which is used to terminate C-style strings). 另外,请考虑用%s %9s替换scanf %s ,以使usernametry永远不会超过9个char (这将是缓冲区溢出,因为第10个char必须为'\\0' ,即空字符,用于终止C样式的字符串)。

You can't compare strings using ==, this is not a that-high-level-language. 您不能使用==比较字符串,这不是那种高级语言。 See strcmp() for comparing strings. 请参阅strcmp()以比较字符串。

Incidentally, what if someone enters a name longer than 10 characters? 顺便说一句,如果有人输入的名称超过10个字符怎么办? You're drifting towards a buffer overflow bug in your code ;-) 您正在向代码中的缓冲区溢出错误过渡;-)

use strcmp() functions to compare 2 strings instead of == 使用strcmp()函数比较2个字符串而不是==

use of == is wrong because in this case you compare address of usernametry and username and of course they are always differents. ==使用是错误的,因为在这种情况下,您需要比较usernametryusername地址,当然它们总是不同的。

if(strcmp(usernametry, username) == 0) // return 0 if equal !=0 if not equal

使用strcmp比较两个字符串:

if(!strcmp(usernametry,username))

Your variables are not the same pointer. 您的变量不是同一指针。

Replace by: 替换为:

if (!strcmp(usernametry, username))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM