Reputation: 1302
I'm using a struct like below:
struct Employee{
string id;
string name;
string f_name;
string password;
};
I wanna have a for loop and every time that I increment i I want to make an object from my struct like this:
for(int i= 0; i<5; i++){
struct Employee Emp(i) = {"12345", "Naser", "Sadeghi", "12345"};
}
All I want is to have objects which are name differently by adding i's value to the end of their names every time like Emp1.
Upvotes: 1
Views: 168
Reputation: 1689
C++ doesn't have exact functionality that you ask for. For keepings things together you need to use arrays or other containers. Then, for access you have to use indexers.
Below is working solution for you question (also here):
#include <vector>
#include <iostream>
#include <string>
struct Employee {
std::string id;
std::string name;
std::string f_name;
std::string password;
};
int main() {
std::vector<Employee> employees; // vector for keeping elements together
for (int i = 0; i<5; i++) {
// push_back adds new element in the end
employees.push_back(Employee{ "12345", "Naser", "Sadeghi", "12345" });
}
std::cout << employees.size() << std::endl; // 5 returns how many elements do you have.
std::cout << employees[0].name; // you access name field of first element (counting starts from 0)
return 0;
}
Upvotes: 4