C program loops indefinitely

让人想犯罪 __ 提交于 2019-12-12 00:36:18

问题


When I run my program it asks for the password indefinitely. I enter the correct password but it simply loops back. There were no errors while I was compiling. To compile, I used:

gcc -ansi -W -Wall -pedantic -o prog myProgram.c
chmod +x prog

I am running ubuntu trusty. Here is the code related to the password:

char string[100] = "";

int main(void)
{
    char correctPassword[25] = "myPassword";
    char password[25] = "";

    system("clear");

    printf("Enter your password:\n");
    scanf("%s", password);

    if (password == correctPassword)
    {
        system("clear");
        printf("Enter a string:\n");
        scanf("%s", string);
    }
    else
    {
        system("clear");
        printf("Sorry, incorrect password\n");
        system("pause");
        main();
    }

updated code:

char string[100] = "";

int main(void)
{
    char correctPassword[25] = "myPassword";
    char password[25] = "";
    int ret;

    system("clear");

    printf("Enter your password:\n");
    scanf("%s", password);

    ret = strcmp(password, correctPassword);
    if (ret == 0)
    {
        system("clear");
        printf("Enter a string:\n");
        scanf("%s", string);
    }
    else
    {
        system("clear");
        printf("Sorry, incorrect password\n");
        system("pause");
        main();
    }
    return 0;
}

edit 2: i think this is beyond solved now, how do i mark it as such?


回答1:


This line

if (password == correctPassword)

does not do what you think it does. It isn't comparing the strings, it is comparing the memory address of the first character of each string. If you want to compare the strings, you want to use strcmp, which you can read about here: http://www.tutorialspoint.com/ansi_c/c_strcmp.htm

EDIT In response to the change in the code; you have the line

if(ret = 0)

You want

if(ret == 0)

I'm assuming this is a typo.




回答2:


Add an ampersand in the scanf statement.

scanf("%s", &password);


来源:https://stackoverflow.com/questions/24067488/c-program-loops-indefinitely

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!