首页 > 解决方案 > 如何检查密码直到正确?

问题描述

我正在编写一个程序来读取密码,直到密码正确为止。我对如何在此使用循环感到困惑。

#include <stdio.h>
#include <cs50.h> //cs library Harvard for getting input of string from the user
#include <string.h>

int main(void) 
{ 
    string first="hello"; 
    string check = get_string("Hello! \n, enter password ,"); //gets the string, input from the user.
    if (strcmp(first, check) == 0)
    { 
        printf("Welcome \n"); 
    } 
    else 
    {
        printf("\n wrong pwd, good bye \n");
    }//I want to put this part in loop until the correct pwd is entered.
} 

标签: cloopspasswordscs50

解决方案


您的问题将使用无限循环来解决,该循环将一直运行,直到用户输入正确的密码。
因此,对于此任务,请附上您的 if-else 语句并在无限 while 循环中打印,一旦用户获得正确的密码,该循环就会中断。

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

int main(void) 
{ 
  string first="hello"; 
  while(1)
  {
    string check = get_string("Hello! \n, enter password ,");
    if (strcmp(first, check) == 0)
    { 
      printf("Welcome \n"); 
      break;
    }
    else 
    {
      printf("\n wrong pwd, good bye \n");
    }
  }
}

推荐阅读