So my question is , how do I make for loop to automatize input of data in different structures, so I dont have to write cin>>a1 cin >>a2..... large amount of times?
The same way as you'd do it for any other type of variable: create an array vector of them, and use a loop, incrementing the array vector index each time.
Hmm, do you have any example where I can see how to declare that properly...
Like i know how to make for loop, but how do i make etc. 5 times repeatedly inputs for 5 different structures with for loop
#include <iostream>
#include <vector>
#include <string>
usingnamespace std;
struct Thing
{
int number;
string name;
void input();
};
void Thing::input()
{
cout << "Enter a number: "; cin >> number; cin.ignore( 1000, '\n' );
cout << "Enter a name: "; getline( cin, name );
}
int main()
{
int N;
cout << "How many things do you want? "; cin >> N;
vector<Thing> things( N );
for ( int i = 0; i < N; i++ ) things[i].input();
cout << "Your entries are:\n";
for ( Thing t : things ) cout << t.number << " " << t.name << '\n';
}
How many things do you want? 3
Enter a number: 123
Enter a name: Donald Trump
Enter a number: 456
Enter a name: Vladimir Putin
Enter a number: 789
Enter a name: Uncle Tom Cobley and all
Your entries are:
123 Donald Trump
456 Vladimir Putin
789 Uncle Tom Cobley and all
And here's the version for those who insist on std:: and const-correctness and initialising all variables, etc.
Edit:
When i add more int than one in "struct" I get this error:
Warning C26495 Variable 'Thing::number3' is uninitialized. Always initialize a member variable (type.6)
(i get this error for every integer, like number2,number3,number4...
for (i = 0; i <= N; i++)
That will loop N+1 times ... you have only allowed for N. Change <= to <.
cin.ignore(1000, '\n');
This should go after cin >> lines, NOT after getline() input. Its purpose is to clear the newline character from the input buffer, which cin>> alone would not do.