C++ 我应该用什么代替#define

Tiv*_*ivi 3 c++ expression constants

我想用 cin 运算符从控制台给出一个值,而不是使用 #define N 6。我试过了,但我收到“表达式必须具有常量值”错误消息。我应该如何通过其他方式做到这一点?

谢谢你的回答!

示例代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

Iva*_*nov 5

定义与预处理器一起展开。实际上,#define N 6意味着N代码中所有出现的都将替换为6,从而替换cin >> Ncin >> 6

解决方案是创建N一个变量:

int N;
cin >> N;
// do whatever you want with N
Run Code Online (Sandbox Code Playgroud)

但是,请注意,在这种情况下,这Person people[N]是一个可变大小的数组(即,在编译时不知道其大小。它是非标准的 C++,您应该避免使用它。考虑使用vector代替——它基本上是一个可变大小的数组标准库中的数组。

cin >> N;
vector<Person> people(N);
...
cin >> people[i].name;
Run Code Online (Sandbox Code Playgroud)