从用户那里获取密码

Getting the password from the user

在此代码中,我试图获取用户的信息,然后通过要求用户输入密码来证明该用户是否正确。

#include <stdio.h>
#include <cs50.h>

//defaults
int acc_user = 0;
string password_user = "" ;
string name_user = "";
int initial_user = 0 ; 

//decalration
void menu();
int select_acc();
int other_info();
int pinTry();

这里是函数的开始,other_info()是访问数据库获取他们的信息。之后打印用户名和pinTry()是为了确认密码继续下一步。

//start 
int main ()
{
    other_info();
    printf("Hello , %s\n" , name_user);
    pinTry();
};
void menu()
{
    //display
    printf("1. Balance\n2. Cash withdrawal\n3. Cash deposition\n4. Quit\n");
}
int other_info()
{
    //gets all the info of the acc 
    int i ;
    int acc[6] = {12341 ,12342 ,12342 ,12344,12345 };
    string name[5] = {"aabb" , "ccdd" ,"eeff","gghh","iijj"};
    string password[6] = {"a1b2c3" , "a2b2c3" ,"A3b2c3" , "A4b2c3" , "A5b2c3" };
    int initial[6] =  {5000 , 1000 , 25000 , 700 , 100000};
    i = select_acc();
    return acc_user = acc[i] , name_user = name[i] , password_user = password[i] , initial_user = initial[i] ; 
}
int select_acc()
{
    // finding the account and the other information 
    int acc , i ; 
    printf("Account number: ");
    scanf("%d\n" , &acc);
    if (acc == 12341 )
    { 
        i = 0 ;
    }
    else if (acc == 12342)
    {
        i = 1; 
    }
    else if (acc == 12343 )
    {
        i = 2;
    }
    else if (acc == 12344)
    {
        i = 3;
    }
    else if (acc == 12345)
    {
        i = 4;
    }
    return i ;
};

这是我尝试比较密码的部分。

int pinTry()
{
    string input,pin = password_user;
    int pinCount=0;
    while(pinCount <3)
    {
        printf("Enter your pin: ");
        scanf("%s",input);
        pinCount++;
        if(input = pin)
        {
            printf("Success\n");
        }
        else
        {
            printf("Incorrect pin\n");
        }

    }
    if(pinCount == 3)
    {
        printf("\nToo many incorrect pins, terminating..\n");
        printf("Password is : %s" , password_user);
        return 1;
    }
};

在此代码中,问题在到达 pinTry() 时开始,我不知道为什么,但错误是分段错误(核心已转储)。我可以知道我做错了什么吗?

string input,pin = password_user;

stringcs50.h 中定义为 char *,这意味着您将输入分配为

char *input;

由于此变量未初始化,它指向随机内存。

当行

scanf("%s",input);

已达到,您尝试将读取的数据放入随机内存位置,导致段错误。

cs50.h 库提供了一个 GetString() 函数供您使用。替换

scanf("%s",input);

input = GetString();