c - 为什么程序中的for循环不能正常工作。它显示正确的输出但给出奇怪的输出
问题描述
#include<stdio.h>
#include<字符串.h>
int main() {
char username[5][10]={"akshay","shubham","gaurav","rahul","amit"};
int i,a=1;
char urname[10];
char pass[10];
printf("enter the Username : ");
scanf("%s",urname);
printf("enter the passwword : ");
scanf("%s",pass);
for(i=0;i<5;i++)
{
if(strcmp(&username[i][0],urname)==0) //username check
{
if(strcmp("helloworld",pass)==0) //password check
{
printf("correct username");
break;
}
else
printf("wrong pass");
break;
}
else
printf(" wrong username");
}
return 0;
}
//我想创建一个登录页面,但从某种意义上说它无法正常工作,请帮助我...
解决方案
您的代码有几个问题。首先,10的数组大小对于类似 的字符串是不够的"helloworld"
,我们看到其中出现了 10 个字符。您没有计算'\0'
字符串末尾的字节。有关详细信息,请参阅此:符号 \0 在字符串文字中的含义是什么?
发现用户名不匹配后,您也会立即显示错误。最后,您应该在检查username[][]
数组中的每个条目并可能设置一个标志之后才这样做。
#include <stdio.h>
#include <string.h>
int main(void)
{
char username[5][10] = {"akshay", "shubham", "gaurav", "rahul", "amit"};
int i, uname_flag = 0;
char urname[11];
char pass[11];
printf("enter the Username : ");
if (scanf("%10s", urname) != 1) // limit characters to be read to 10, to avoid buffer overflow
// also check the return value of scanf for input failure
{
return 1;
}
printf("enter the passwword : ");
if (scanf("%10s", pass) != 1)
{
return 1;
}
for (i = 0; i < 5; i++)
{
if (strcmp(username[i], urname) == 0) //username check
{
uname_flag = 1; // username is correct
if (strcmp("helloworld", pass) == 0) //password check
{
printf("correct username & pass");
break;
}
else
{
printf("wrong pass");
break;
}
}
}
if (uname_flag == 0) // check outside the loop
{
printf("wrong username\n");
}
return 0;
}
推荐阅读
- css - 如何在反应中更改 ag-grid 的 bg 颜色?
- c# - 如何直接从 datagridview 单元格更新 SQL 记录,而不使用文本框?
- c# - InvalidOperationException:列出但应该是 vm 值
- css - 为什么弹性按钮的孩子不能伸展到全高?
- c - 找不到英特尔 C++ 编译器 17.0(平台工具集 = '英特尔 C++ 编译器 17.0')的构建工具
- python - 使用 json 从 instagram 收集数据
- scorm - SCORM 内容中的 AJAX
- azure - Azure 管道 BatchScript 任务未在其部署到的计算机上运行脚本
- asp.net - Angular 8 httpclient如何发送JSON标头
- latex - 如何在 dev.to 编辑器中使用 Latex?