fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <fstream>
  4.  
  5. using namespace std;
  6.  
  7. struct User {
  8. string username;
  9. string password;
  10. };
  11.  
  12. // Function to register a new user
  13. void registerUser() {
  14. User newUser;
  15. cout << "Enter username: ";
  16. cin >> newUser.username;
  17. cout << "Enter password: ";
  18. cin >> newUser.password;
  19.  
  20. ofstream file("users.txt", ios::app);
  21. file << newUser.username << ":" << newUser.password << endl;
  22. file.close();
  23.  
  24. cout << "Registration successful!" << endl;
  25. }
  26.  
  27. // Function to login an existing user
  28. void loginUser() {
  29. string username, password;
  30. cout << "Enter username: ";
  31. cin >> username;
  32. cout << "Enter password: ";
  33. cin >> password;
  34.  
  35. ifstream file("users.txt");
  36. string line;
  37. bool found = false;
  38.  
  39. while (getline(file, line)) {
  40. size_t colonPos = line.find(":");
  41. string storedUsername = line.substr(0, colonPos);
  42. string storedPassword = line.substr(colonPos + 1);
  43.  
  44. if (username == storedUsername && password == storedPassword) {
  45. found = true;
  46. break;
  47. }
  48. }
  49.  
  50. file.close();
  51.  
  52. if (found) {
  53. cout << "Login successful!" << endl;
  54. } else {
  55. cout << "Invalid username or password." << endl;
  56. }
  57. }
  58.  
  59. int main() {
  60. int choice;
  61. cout << "1. Register" << endl;
  62. cout << "2. Login" << endl;
  63. cout << "Enter your choice: ";
  64. cin >> choice;
  65.  
  66. if (choice == 1) {
  67. registerUser();
  68. } else if (choice == 2) {
  69. loginUser();
  70. } else {
  71. cout << "Invalid choice." << endl;
  72. }
  73.  
  74. return 0;
  75. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
1. Register
2. Login
Enter your choice: Invalid choice.