2017-01-15 20 views
-3

Когда пользователь вводит неверный пароль, код должен перезагрузиться, когда они попытались в два раза прекратить код, но в моем коде, когда пользователь вводит неверную информацию и передает пароли_треты он продолжает идти все остальное, кажется, работает просто отличноБез использования цикла, как я могу выполнить итерацию кодовой инструкции

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 

    string myusername; 
    string mypassword; 
    bool Access_granted; 
    int password_attempts; 
    cout << "Enter your username: "; 
    cin >> myusername; 
    cout << "Enter your password: "; 
    cin >> mypassword; 
    if (myusername == "veasy62" && mypassword == "a65908") { 
     Access_granted = true; 
     cout << "Access granted veasy62\n"; 
    } 
    else if (myusername == "tveasy62" || mypassword == "a1065908") { 
     Access_granted = true; 
     cout << "Access granted tveasy62\n"; 
    } 
    else { 
     Access_granted = false; 
     cout << password_attempts; 
     cout << "Access Denied, Sorry try again\n"; 
     if (Access_granted == false) { 
      if (password_attempts = 2) { 
       password_attempts = password_attempts + 1; 
       return main(); 
      } 
      else { 
       cout << "Sorry you have ran out of attempts\n"; 
      } 
     } 
    } 
} 
+9

Вы не можете называть главное, как обычную функцию. §3.6.1 –

+5

Почему вы не можете использовать циклы? Разбиты ли ваши ключи f и w? –

+3

Все остальное в стороне, вероятно, поможет, если вы использовали 'password_attempts == 2' вместо' password_attemps = 2'. – Dolda2000

ответ

1

вместо возвращения вы можете использовать Гото, если вы не хотите использовать loop.You можно использовать «Endl» вместо «\ п» .Вы можно попробовать это -

#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    string myusername; 
    string mypassword; 
    bool Access_granted; 
    int password_attempts=0; 
    restart: 
    cout << "Enter your username: "; 
    cin >> myusername; 
    cout << "Enter your password: "; 
    cin >> mypassword; 
    if(myusername == "veasy62" && mypassword == "12") 
    { 
     Access_granted = true; 
     cout<<"Access granted veasy62" << endl; 
    } 
    else if (myusername == "tveasy62" || mypassword == "a1065908") 
    { 
     Access_granted = true; 
     cout<<"Access granted tveasy62" << endl; 
    } 
    else 
    { 
     Access_granted = false; 


     if(Access_granted == false) 
     { 
      if(password_attempts < 2) 
      { 
       cout << "Access Denied, Sorry try again" << endl; 
       password_attempts = password_attempts + 1; 
       cout << "you have remaining " << 2-password_attempts << " time chances after this attempt" << endl; 
       goto restart; 
      } 
      else 
      { 
       cout << "Sorry you have ran out of attempts\n"; 
      } 
     } 
    } 

    return 0; 
} 
+0

Нет, пожалуйста, не используйте 'goto'. – PaulMcKenzie

+0

@PaulMcKenzie, в чем проблема с использованием «goto»? пожалуйста, объясните –

+0

[Кодирование спагетти] (https://en.wikipedia.org/wiki/Spaghetti_code). Вы хотите поощрить это? – PaulMcKenzie

2

Ваш код получил Litttle buggy. Вместо & & вы использовали || также insteas из == 2 вы назначили = 2 к password_attempts, если условие Ненужные если (ложное условие проверки) я удалил все те, и вот код для задачи вы хотите достичь

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 

    string myusername; 
    string mypassword; 
    bool Access_granted; 
    int password_attempts=0; 

    HERE : cout << "Enter your username: "; 
    cin >> myusername; 
    cout << "Enter your password: "; 
    cin >> mypassword; 
    if (myusername == "veasy62" && mypassword == "a65908") { 
     Access_granted = true; 
     cout << "Access granted veasy62\n"; 
     break; 
    } 
    else if (myusername == "tveasy62" && mypassword == "a1065908") { 
     Access_granted = true; 
     cout << "Access granted tveasy62\n"; 
     break; 
     } 
    else { 
     password_attempts = password_attempts + 1; 
     Access_granted = false; 
     cout << password_attempts; 
     cout << "Access Denied, Sorry try again\n"; 

      if (password_attempts == 2) { 
       cout << "Sorry you have ran out of attempts\n"; 
       return 0; 

       //to exit main().can also use exit(0) using additional libraries 
      } 
      else{ 
      goto HERE; 
     } 
     } 

} 
+1

ОП сказал, что ему запрещено использовать какие-либо петли. –

+0

Ohk меняет код. @Michael Albers – minigeek

1

Так вы говорите, вы не можете использовать циклы. Ну вот решение, которое использует рекурсивный шаблон. Нет «gotos», и его легко настроить, изменив параметр шаблона на большее число.

#include <string> 
#include <iostream> 

template <int attempts> 
struct password_entry 
{ 
    static bool get_entry(std::string& myusername, std::string& mypassword) 
    { 
     std::cout << "Enter your username: "; 
     std::cin >> myusername; 
     std::cout << "Enter your password: "; 
     std::cin >> mypassword; 
     if (myusername == "veasy62" && mypassword == "12") 
     { 
      std::cout << "Access granted veasy62" << std::endl; 
      return true; 
     } 
     if (attempts > 1) 
      std::cout << "Access denied. You have " << attempts - 1 << " attempts remaining\n"; 
     return password_entry<attempts - 1>::get_entry(myusername, mypassword); 
    } 
}; 

template <> 
struct password_entry<0> 
{ 
    static bool get_entry(const std::string&, const std::string&) 
    { 
     std::cout << "Sorry you have ran out of attempts\n"; 
     return false; 
    } 
}; 


int main() 
{ 
    std::string mypass, myuser; 

    // max 2 attempts 
    bool access_granted = password_entry<2>::get_entry(myuser, mypass); 
    if (access_granted) 
     std::cout << "Welcome current user"; 
    else 
     std::cout << "Please call 555-5555 to reset your password"; 
} 

Чтобы настроить количество попыток, нужно просто изменить параметр параметров шаблона password_entry.

Live Example

Edit: Скорректированный код не использовать конструктор.

+0

Предположим, что _password entry_ ожидает ввода пользователем в реальном сценарии, ваши предложения сделать это в конструкторе? Я думаю, что это не очень хорошая идея. – skypjack

+0

Предположим, мы могли бы использовать циклы, как и любая реальная программа. Вы получаете то, за что платите - нет циклов, меньше функциональности. – PaulMcKenzie

+0

Я скорректировал код, чтобы использовать статическую функцию, а не конструктор. – PaulMcKenzie

0

так что я понимаю из вас вопрос, который вы хотите, чтобы пользователь вводил свой пароль два раза, и если оба были неправы, закончить программу правильно? , тогда вы можете написать вот так.

Edited :)

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 

    string myusername; 
    string mypassword; 
    bool Access_granted; 
    int password_attempts=0; 




     cout << "Enter your username: "; 
     cin >> myusername; 
     cout << "Enter your password: "; 
     cin >> mypassword; 
     if (myusername == "veasy62" && mypassword == "a65908") { 
      Access_granted = true; 
      cout << "Access granted veasy62\n"; 
     } 
     else if (myusername == "tveasy62" || mypassword == "a1065908") { 
      Access_granted = true; 
      cout << "Access granted tveasy62\n"; 
      system("pause"); 
      return 0; 
     } 
     else { 
      Access_granted = false; 
      cout << "Access Denied, Sorry try again\n"; 
      cout << "Enter your username: "; 
      cin >> myusername; 
      cout << "Enter your password: "; 
      cin >> mypassword; 
      if (myusername == "veasy62" && mypassword == "a65908") { 
       Access_granted = true; 
       cout << "Access granted veasy62\n"; 
      } 
      else if (myusername == "tveasy62" || mypassword == "a1065908") { 
       Access_granted = true; 
       cout << "Access granted tveasy62\n"; 
       system("pause"); 
       return 0; 
      } 
      else 
      { 


        cout << "Sorry you have ran out of attempts\n"; 
        cout << "Access Denied"; 
        system("pause"); 
        return -1; 
       } 
      } 



    return 0; 
} 
+0

ОП сказал, что ему не разрешено использовать какие-либо петли. –

+1

Никаких петель не допускается! – minigeek

+0

Я просто редактирую. – Sesoin

0
#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    string myusername; 
    string mypassword; 
    bool Access_granted; 
    int password_attempts=0; 
    cout << "Enter your username: "; 
    cin >> myusername; 
    cout << "Enter your password: "; 
    cin >> mypassword; 
    if (myusername == "veasy62" && mypassword == "a65908") { 
     Access_granted = true; 
     cout << "Access granted veasy62\n"; 
    } 
    else if (myusername == "tveasy62" || mypassword == "a1065908") { 
     Access_granted = true; 
     cout << "Access granted tveasy62\n"; 
    } 
    else { 
     Access_granted = false; 
     cout << password_attempts; 
     cout << "Access Denied, Sorry try again\n"; 
     if (Access_granted == false) { 
      if (password_attempts <=2) { 
       password_attempts = password_attempts + 1; 
       return main(); 
      } 
      else { 
       cout << "Sorry you have ran out of attempts\n"; 
      } 
     } 
    } 
} 
+1

Вы не можете вызвать 'main' из программы на C++. Об этом уже говорилось в основных комментариях, приведенных выше @CaptainGriraffe с цитированием из стандартного документа C++. – PaulMcKenzie

0

Использование Гото Или, если вы хотите попробовать модули рекурсивный function.it будет работать, как вы пытаетесь сделать.

public int accessAllowed(int notrys=0) 
{ 
if(notrys<2) 
return 0; 

string username,password; 

//take username password 

If(//condition 1) 
return 1; 

else if(//condition 2) 
return 1; 

else 
return accessAllowed(notrys+1); 
} 

Хотя goto будет эффективным.

Также есть много ошибок в коде

  1. Nooftrys не инициализирован (я думаю, что вам нужно, как 0 inititial значение)
  2. || вместо & &
  3. = 2 при проверке переполнения попыток используйте < 2 для 2 попыток.