67,058 views
45 votes
45 votes
Please help me C++ coding

1. Make an inventory program for products. The program should first ask the user to prompt

USERNAME and PASSWORD. If both are correct proceed to the program if not use Try-throw-

catch and ask the user to enter the USERNAME and PASSWORD up to 3times only.

User Norbert Hartl
by
2.4k points

1 Answer

8 votes
8 votes

Answer:

#include <iostream>

#include <string>

const std::string USERNAME = "admin";

const std::string PASSWORD = "password";

int main()

{

int attempts = 0;

bool success = false;

while (attempts < 3 && !success)

{

std::string username, password;

std::cout << "Enter username: ";

std::cin >> username;

std::cout << "Enter password: ";

std::cin >> password;

try

{

if (username != USERNAME || password != PASSWORD)

{

throw std::invalid_argument("Invalid username or password");

}

success = true;

}

catch (const std::invalid_argument& e)

{

std::cout << "Error: " << e.what() << std::endl;

attempts++;

}

}

if (success)

{

// Proceed to the program

std::cout << "Access granted" << std::endl;

}

else

{

std::cout << "Access denied" << std::endl;

}

return 0;

}

User Buddhi Weerasinghe
by
3.1k points