[英]How to get integer and string input using scanf?
I have a problem in C language我的 C 语言有问题
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char usrname[17] = "nsa-secret-agent";
char password[9] = "marshal41";
char usr[512], pass[512];
printf("username: ");
scanf("%[^\n]%*c", usr);
printf("password: ");
scanf("%[^\n]%*c", pass);
printf("%s\n", usr);
printf("%s\n", pass);
if (strcmp(usrname, usr) == 0 && strcmp(password, pass) == 0){
printf("You Have Successfully Logged In!\n");
}
else{
printf("username or password not found!\n");
exit(0);
}
return 0;
}
When I run this code it runs without any errors but when give input like below:当我运行此代码时,它运行时没有任何错误,但是当给出如下输入时:
username: nsa-secret-agent
password: marshal41
nsa-secret-agent
marshal41
username or password not found!
I am giving correct credentials but still it's showing error我提供了正确的凭据,但仍然显示错误
Your arrays for usrname
and password
are off by one:您的 arrays 的
usrname
和password
减一:
char usrname[17] = "nsa-secret-agent";
char password[9] = "marshal41";
These are short one byte for the zero terminator which makes the comparison later fail.这些是零终止符的短一个字节,这使得以后的比较失败。 Either add one or just use
添加一个或只使用
char usrname[] = "nsa-secret-agent";
char password[] = "marshal41";
or you could even use或者你甚至可以使用
char *usrname = "nsa-secret-agent";
char *password = "marshal41";
since the strings are not modified.因为字符串没有被修改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.