I am still at beginner stage in c++ and I am always curious about good/best coding method.
let's say I have a program which allows a users to edit the salary of a employee.
1)The system will prompt the user which to key in a employee's name first.
2)The system will then check whether the username exist anot.
3)If the username existed, the system will then allow the user to change the employee's
salary.
the salary and the name of the person is stored in a text file.
e.g employeeInfo.txt formatted by(name salary)
john 1000
mary 2000
bob 3000
user.h
#ifndef user_user_h
#define user_user_h
#include <iostream>
class user {
public:
user(std::string userName,std::string salary);
std::string getUserName();
std::string getSalary();
void setUserName(std::string userName);
void setSalary(std::string salary);
private:
std::string userName,salary;
};
#endif
user.cpp
#include "user.h"
#include <iostream>
#include <string>
using namespace std;
user::user(string userName,string salary) {
setUserName(userName);
setSalary(salary);
};
string user::getUserName() {
return userName;
}
string user::getSalary() {
return salary;
}
void user::setUserName(std::string userName) {
this->userName = userName;
}
void user::setSalary(std::string salary) {
this->salary = salary;
}
main.cpp
#include "user.h"
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <stdio.h>
#include <string.h>
using namespace std;
int main(){
vector<user> userDetails;
string line;
string userName;
string salary;
ifstream readFile("employeeInfo.txt");
while(getline(readFile,line)) {
stringstream iss(line);
iss >> userName >> salary;
//consturctor
user employeeDetails(userName,
salary
);
userDetails.push_back(employeeDetails);
}
readFile.close();
string name;
cout << "Please enter a user name\n";
cin >> name;
for (int i =0; i<userDetails.size(); i++) {
//search if there's a match
if (userDetails[i].getUserName() == name) {
string newSalary;
cout << "Please enter a new salary" << endl;
cin >> newSalary;
userDetails[i].setSalary(newSalary);
}
}
//display to see if the salary gets updated
for (int i=0; i<userDetails.size(); i++) {
cout << userDetails[i].getSalary << "\n";
}
}
well my question is I am not really sure if my code(shown below) is the worst method to search for a record in a vector and match it against the input of the user
and I would like to know is there any way to improve my codes and gather some tips and ideas from you guys if this is the worst method to search for a record in a vector.
thanks.
//search for existing username
for (int i =0; i<userDetails.size(); i++) {
if (userDetails[i].getUserName() == name) {
//do stuff
}
}