首页 > 解决方案 > 为什么程序中的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;

    }  

//我想创建一个登录页面,但从某种意义上说它无法正常工作,请帮助我...

标签: c

解决方案


您的代码有几个问题。首先,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;
}

推荐阅读