Улучши код: -Сделай так что бы файл users.txt создавался автоматически на диске C и что…
- User
Улучши код: -Сделай так что бы файл users.txt создавался автоматически на диске C и что бы программа могла в него внести данные для работы программы.load_user_info -Проверь код все ли ему хватает по логике действий.
#include #include #include #include #include #include #include #include
using namespace std;
//структура для хранения информации о пользователях struct User { int id; string name; string masked_ip; int port; };
//генерация случайного id пользователя int generate_id(set& used_ids) { int id; do { id = rand() % 1000000000; } while (used_ids.find(id) != used_ids.end()); used_ids.insert(id); return id; }
//генерация маскированного ip-адреса пользователя string generate_masked_ip(set& used_ips) { int number; stringstream ss; for (int i = 0; i < 9; i++) { number = rand() % 10; ss << number; } string masked_ip = ss.str(); while (used_ips.find(masked_ip) != used_ips.end()) { masked_ip = generate_masked_ip(used_ips); } used_ips.insert(masked_ip); return masked_ip; }
//функция для сохранения информации о пользователе в файл void save_user_info(vector& users) { ofstream file("users.txt"); if (!file.is_open()) { throw runtime_error("Cannot open file for writing"); } for (User user : users) { file << user.id << ", " << user.name << ", " << user.masked_ip << ", " << user.port << endl; } file.close(); }
//функция для загрузки информации о пользователях из файла void load_user_info(vector& users, set& used_ids, set& used_ips) { ifstream file("users.txt"); if (!file.is_open()) { throw runtime_error("Cannot open file for reading"); } string line; while (getline(file, line)) { User user; int pos; pos = line.find(", "); user.id = stoi(line.substr(0, pos)); if (used_ids.find(user.id) != used_ids.end()) { throw runtime_error("Duplicated user id : " + to_string(user.id)); } used_ids.insert(user.id); line.erase(0, pos + 1); pos = line.find(", "); user.name = line.substr(1, pos - 2); line.erase(0, pos + 1); pos = line.find(", "); user.masked_ip = line.substr(1, pos - 2); if (used_ips.find(user.masked_ip) != used_ips.end()) { throw runtime_error("Duplicated user ip: " + user.masked_ip); } used_ips.insert(user.masked_ip); line.erase(0, pos + 1); user.port = stoi(line); users.push_back(user); } file.close(); }
//функция для поиска пользователя по id User find_user_by_id(vector& users, int id) { for (User user : users) { if (user.id == id) { return user; } } User user; user.id = -1; return user; }
//функция для поиска пользователя по маскированному ip User find_user_by_masked_ip(vector& users, string masked_ip) { for (User user : users) { if (user.masked_ip == masked_ip) { return user; } } User user; user.id = -1; return user; }
//функция для проверки корректности порта bool is_port_correct(int port) { if (port < 1024 || port > 65535) { return false; } return true; }
//функция для добавления нового пользователя void add_new_user(vector& users, set& used_ids, set& used_ips) { User user; user.id = generate_id(used_ids); cout << "ID user: " << user.id << endl; cout << "Enter username: "; cin >> user.name; user.masked_ip = generate_masked_ip(used_ips);
while (true) { cout << "Enter user port: "; cin >> user.port; if (is_port_correct(user.port)) { break; } else { cout << "Incorrect port.Please try again." << endl; } } users.push_back(user); save_user_info(users); cout << "User added successfully" << endl;}
//функция для отправки сообщения от пользователя sender пользователю recipient void send_message(vector& users, int sender_id, string recipient_ip, string message) { User sender = find_user_by_id(users, sender_id); if (sender.id == -1) { throw runtime_error("User with this id was not found"); } User recipient = find_user_by_masked_ip(users, recipient_ip); if (recipient.id == -1) { throw runtime_error("User with this ip was not found"); } cout << "Message from " << sender.name << " to " << recipient.name << ": " << message << endl; }
//главный метод программы int main() { vector users; set used_ids; set used_ips; load_user_info(users, used_ids, used_ips);
int choice; cout << "1.Find user by id" << endl; cout << "2.Add new user" << endl; cout << "3.Send message" << endl; cout << "Your choice: "; cin >> choice; try { if (choice == 1) { int id; cout << "Enter user id: "; cin >> id; User found_user = find_user_by_id(users, id); if (found_user.id == -1) { cout << "User with this id was not found" << endl; } else { cout << "User found: " << endl; cout << "ID: " << found_user.id << endl; cout << "Name: " << found_user.name << endl; cout << "IP: " << found_user.masked_ip << endl; cout << "Port: " << found_user.port << endl; } } else if (choice == 2) { add_new_user(users, used_ids, used_ips); } else if (choice == 3) { int sender_id; cout << "Enter sender id: "; cin >> sender_id; string recipient_ip; cout << "Enter recipient masked ip: "; cin >> recipient_ip; string message; cout << "Enter message: "; cin.ignore(); getline(cin, message); send_message(users, sender_id, recipient_ip, message); } else { throw invalid_argument("Invalid choice: " + to_string(choice)); } } catch (exception& e) { cerr << "Error: " << e.what() << endl; exit(1); } return 0;}
- Assistant
#include #include #include #include #include #include #include #include
using namespace std;
//структура для хранения информации о пользователях struct User { int id; string name; string masked_ip; int port; };
//генерация случайного id пользователя int generate_id(set& used_ids) { int id; do { id = rand() % 1000000000; } while (used_ids.find(id) != used_ids.end()); used_ids.insert(id); return id; }
//генерация маскированного ip-адреса пользователя string generate_masked_ip(set& used_ips) { int number; stringstream ss; for (int i = 0; i < 9; i++) { number = rand() % 10; ss << number; } string masked_ip = ss.str(); while (used_ips.find(masked_ip) != used_ips.end()) { masked_ip = generate_masked_ip(used_ips); } used_ips.insert(masked_ip); return masked_ip; }
//функция для сохранения информации о пользователе в файл void save_user_info(const vector& users) { ofstream file("C:/users.txt"); if (!file.is_open()) { throw runtime_error("Cannot open file for writing"); } for (const User& user : users) { file << user.id << ", " << user.name << ", " << user.masked_ip << ", " << user.port << endl; } file.close(); }
//функция для загрузки информации о пользователях из файла void load_user_info(vector& users, set& used_ids, set& used_ips) { ifstream file("C:/users.txt"); if (!file.is_open()) { ofstream new_file("C:/users.txt"); new_file.close(); } else { string line; while (getline(file, line)) { User user; int pos; pos = line.find(", "); user.id = stoi(line.substr(0, pos)); if (used_ids.find(user.id) != used_ids.end()) { throw runtime_error("Duplicated user id : " + to_string(user.id)); } used_ids.insert(user.id); line.erase(0, pos + 1); pos = line.find(", "); user.name = line.substr(1, pos - 2); line.erase(0, pos + 1); pos = line.find(", "); user.masked_ip = line.substr(1, pos - 2); if (used_ips.find(user.masked_ip) != used_ips.end()) { throw runtime_error("Duplicated user ip: " + user.masked_ip); } used_ips.insert(user.masked_ip); line.erase(0, pos + 1); user.port = stoi(line); users.push_back(user); } file.close(); } }
//функция для поиска пользователя по id User find_user_by_id(const vector& users, int id) { for (const User& user : users) { if (user.id == id) { return user; } } User user; user.id = -1; return user; }
//функция для поиска пользователя по маскированному ip User find_user_by_masked_ip(const vector& users, const string& masked_ip) { for (const User& user : users) { if (user.masked_ip == masked_ip) { return user; } } User user; user.id = -1; return user; }
//функция для проверки корректности порта bool is_port_correct(int port) { if (port < 1024 || port > 65535) { return false; } return true; }
//функция для добавления нового пользователя void add_new_user(vector& users, set& used_ids, set& used_ips) { User user; user.id = generate_id(used_ids); cout << "ID user: " << user.id << endl; cout << "Enter username: "; cin >> user.name; user.masked_ip = generate_masked_ip(used_ips);
while (true) { cout << "Enter user port: "; cin >> user.port; if (is_port_correct(user.port)) { break; } else { cout << "Incorrect port. Please try again." << endl; } } users.push_back(user); save_user_info(users); cout << "User added successfully" << endl;}
//функция для отправки сообщения от пользователя sender пользователю recipient void send_message(const vector& users, int sender_id, const string& recipient_ip, const string& message) { User sender = find_user_by_id(users, sender_id); if (sender.id == -1) { throw runtime_error("User with this id was not found"); } User recipient = find_user_by_masked_ip(users, recipient_ip); if (recipient.id == -1) { throw runtime_error("User with this ip was not found"); } cout << "Message from " << sender.name << " to " << recipient.name << ": " << message << endl; }
//главный метод программы int main() { vector users; set used_ids; set used_ips; load_user_info(users, used_ids, used_ips);
int choice; cout << "1.Find user by id" << endl; cout << "2.Add new user" << endl; cout << "3.Send message" << endl; cout << "Your choice: "; cin >> choice; try { if (choice == 1) { int id; cout << "Enter user id: "; cin >> id; User found_user = find_user_by_id(users, id); if (found_user.id == -1) { cout << "User with this id was not found" << endl; } else { cout << "User found: " << endl; cout << "ID: " << found_user.id << endl; cout << "Name: " << found_user.name << endl; cout << "IP: " << found_user.masked_ip << endl; cout << "Port: " << found_user.port << endl; } } else if (choice == 2) { add_new_user(users, used_ids, used_ips); } else if (choice == 3) { int sender_id; cout << "Enter sender id: "; cin >> sender_id; string recipient_ip; cout << "Enter recipient masked ip: "; cin >> recipient_ip; string message; cout << "Enter message: "; cin.ignore(); getline(cin, message); send_message(users, sender_id, recipient_ip, message); } else { throw invalid_argument("Invalid choice: " + to_string(choice)); } } catch (const exception& e) { cerr << "Error: " << e.what() << endl; exit(1); } return 0;}
- User
Теперь добавь в код: 1-Что бы показывало свой id по которому смогут найти меня. И что бы когда добавили мой id мне пришло уведомление с вопросом добавить пользователя или отменить. 2-Реализуй метод общения чата
- Assistant
//функция для добавления нового пользователя void add_new_user(vector& users, set& used_ids, set& used_ips, int my_id) { User user; user.id = generate_id(used_ids); cout << "ID user: " << user.id << endl; cout << "Enter username: "; cin >> user.name; user.masked_ip = generate_masked_ip(used_ips);
while (true) { cout << "Enter user port: "; cin >> user.port; if (is_port_correct(user.port)) { break; } else { cout << "Incorrect port. Please try again." << endl; } } if (user.id == my_id) { cout << "Do you want to add this user?" << endl; cout << "1. Yes" << endl; cout << "2. No" << endl; int choice; cin >> choice; if (choice == 1) { users.push_back(user); save_user_info(users); cout << "User added successfully" << endl; } else { cout << "User not added." << endl; } } else { users.push_back(user); save_user_info(users); cout << "User added successfully" << endl; }}
//главный метод программы int main() { vector users; set used_ids; set used_ips; int my_id = generate_id(used_ids); cout << "Your id: " << my_id << endl; load_user_info(users, used_ids, used_ips);
int choice; cout << "1.Find user by id" << endl; cout << "2.Add new user" << endl; cout << "3.Send message" << endl; cout << "Your choice: "; cin >> choice; try { if (choice == 1) { int id; cout << "Enter user id: "; cin >> id; User found_user = find_user_by_id(users, id); if (found_user.id == -1) { cout << "User with this id was not found" << endl; } else { cout << "User found: " << endl; cout << "ID: " << found_user.id << endl; cout << "Name: " << found_user.name << endl; cout << "IP: " << found_user.masked_ip << endl; cout << "Port: " << found_user.port << endl; } } else if (choice == 2) { add_new_user(users, used_ids, used_ips, my_id); } else if (choice == 3) { int sender_id; cout << "Enter sender id: "; cin >> sender_id; if (sender_id == my_id) { cout << "You cannot send messages to yourself." << endl; } else { string recipient_ip; cout << "Enter recipient masked ip: "; cin >> recipient_ip; string message; cout << "Enter message: "; cin.ignore(); getline(cin, message); send_message(users, sender_id, recipient_ip, message); } } else { throw invalid_argument("Invalid choice: " + to_string(choice)); } } catch (const exception& e) { cerr << "Error: " << e.what() << endl; exit(1); } return 0;}
//функция для отправки сообщения от пользователя sender пользователю recipient void send_message(const vector& users, int sender_id, const string& recipient_ip, const string& message)