Reputation: 496
I would like to give a value from the console with cin operator instead of using a #define N 6. I've tried it but I get "expression must have constant value" error message. How should I do it by the other way?
Thank you for answers!
Example code:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#define N 6
using namespace std;
typedef struct person {
int roll;
string name;
} Person;
int main() {
int numberofperson;
cout << "Number of people: "; cin >> numberofperson;
srand(time(NULL));
Person people[N];
int i;
for (i = 0; i < numberofperson; i++) {
cout << "Write the " << i + 1 << ". name of the person: ";
cin >> people[i].name;
people[i].roll = rand() % 6 + 1;
cout << "Roll with dice: " << people[i].roll<<endl;
}
return 0;
}
Upvotes: 4
Views: 349
Reputation: 4435
Defines are unrolled with the preprocessor. In fact, #define N 6
means that all occurrences of N
in your code will be replaced by 6
, thus replacing cin >> N
with cin >> 6
.
The solution is to make N
a variable:
int N;
cin >> N;
// do whatever you want with N
However, note that in this case Person people[N]
is a variable-sized array (that is, its size is not known during compilation time. It is non-standard C++ and you should avoid it. Consider using vector instead – it is basically a variable-sized array from the standard library.
cin >> N;
vector<Person> people(N);
...
cin >> people[i].name;
Upvotes: 5