'How can I call out a string from an object array?
I have recently started some OOP in C++, and I was trying to make a small program in Dev-C++ to store arrays of information on employees through a friends function. The code is rough and could use improvements, but I'm not too proficient at it.
#include <iostream>
using namespace std;
class employee{
int id;
string names[5];
float salary;
public:
friend void input();
friend void output();
};
void input(){
employee obj[5];
cout << "enter employee id, name and salary\n";
for(int i=0; i<5; i++){
cin>>obj[i].id>>obj[i].names[i]>>obj[i].salary;
}
}
void output(){
employee obj[5];
for(int i=0; i<5; i++){
cout<<"\nwelcome "<<obj[i].name[i]<<endl<<"your id is: "<<obj[i].id<<" and your salary is: "<<obj[i].salary<<"PKR"<<endl;
}
}
int main(){
input();
output();
}
The particular issue is that it doesn't call out the string names for some reason, and I've tried a lot of different ways to rewrite it. Am I just approaching this wrong?
Solution 1:[1]
employee obj[5];
is local to each functions. You should declare that in main()
and pass that as an argument.
void input(employee obj[]){
cout<<"enter employee id, name and salary\n";
for(int i=0;i<5;i++){
cin>>obj[i].id>>obj[i].names[i]>>obj[i].salary;
}
}
void output(employee obj[]){
for(int i=0;i<5;i++){
cout<<"\nwelcome "<<obj[i].name[i]<<endl<<"your id is: "<<obj[i].id<<" and your salary is: "<<obj[i].salary<<"PKR"<<endl;
}
}
int main(){
employee obj[5];
input(obj);
output(obj);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |