gpt4 book ai didi

c - 我如何处理 C 中的字符串输入?

转载 作者:行者123 更新时间:2023-12-04 11:04:05 26 4
gpt4 key购买 nike

我只是在练习 C,我想制作一个带有用户名和密码的简单登录程序...这是我的代码:

int main(){
char uname, passwd;

printf("Enter your username: ");
scanf("%c", uname);
printf("Enter your password: ");
scanf("%c", passwd);

printf(" \n");

if (uname == "waw" && passwd == "wow"){
printf("You have logged in\n");
} else {
printf("Failed, please try again\n");
}
return 0;
}

然后我在尝试编译它时遇到了这个错误

log.c: In function ‘main’:
log.c:7:10: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%c", uname);
^
log.c:9:10: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
scanf("%c", passwd);
^
log.c:13:14: warning: comparison between pointer and integer
if (uname == "waw" && passwd == "wow"){
^
log.c:13:33: warning: comparison between pointer and integer
if (uname == "waw" && passwd == "wow"){
^

最佳答案

1) 不要读入(扫描)一个字符。你需要一个字符串。使用格式说明符 %s 而不是 %c

2) 使用strcmp比较字符串值

试试这个:

#include <stdio.h>

int main(){
int res;
char uname[40]; // char arrays instead of single char
char passwd[40];

printf("Enter your username: ");
res = scanf("%39s", uname); // Set a maximum number of chars to read to
// 39 to avoid overflow
if (res != 1) exit(1); // Error on stdin. End program

printf("Enter your password: ");
res = scanf("%39s", passwd);
if (res != 1) exit(1); // Error on stdin

printf(" \n");

// Use strcmp to compare values of two strings.
// If strcmp returns zero, the strings are identical
if ((strcmp(uname, "waw") == 0) && (strcmp(passwd, "wow") == 0)){
printf("You have logged in\n");
} else{
printf("Failed, please try again\n");
}
return 0;
}

关于c - 我如何处理 C 中的字符串输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39109280/

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