简单的C ++语法更正

时间:2012-09-26 02:42:33

标签: c++

以下C ++代码有什么问题吗?

int i;
int n;
cout << "a";
cin >> n;
int player[i];
for(i = 0; i <= 3; i++)
{
     player[i] = n;
}

3 个答案:

答案 0 :(得分:1)

为了获得相同的功能,我会这样做:

#define PLAYER_SIZE 4
//Or you can go:
//const int PLAYER_SIZE = 4;
int n = 0; //Don't *need* to = 0 in this case, but good practice.
cout << "a";
cin >> n;
int player[ PLAYER_SIZE ];
for( int i = 0; i < PLAYER_SIZE; ++i )
{
     player[i] = n;
}

由于在这种情况下i&lt; = 3是硬编码的,因此不需要高于4。

答案 1 :(得分:0)

you can't declare index of array as variable

声明一些大小,比如

int player[10];

或使用预处理程序指令

#define i 10
int player[i];

完全

#define i 10
int main()
{
int j;
int n;
cout<<"a";
cin>>n;
int player[i];
for(j=0;j<=3;j++)
{player[j]=n;}
}

答案 2 :(得分:0)

将i初始化为某个东西并将其声明为const然后使用它来表示静态数组的大小是正常的。

如果要在运行时确定大小,则需要使用new运算符并处理堆内存和指针。

const int i = 4; // whatever size
int player[i];

int n;
cin >> n;
cin.ignore(); // important if you plan on using cin again, also think about adding some input checking

for (int x = 0; x < i; ++x ) // for god sakes use ++x
     player[x] = n;
// take note your setting every int in player to the same value of n

只是为了清理一下

const int arraySize = 4;
int playerArray[arraySize];

int input = 0;
for ( int i = 0; i < arraySize; ++i )
    {
    cin >> input;
    cin.ignore(); // still no error checking
    playerArray[i] = input;
    }

此代码允许为数组中的每个int输入不同的int。