得到错误C2062:使用教科书中的代码输入“int”意外

时间:2013-12-21 03:00:39

标签: c++ visual-c++ pointers

尝试使用基本指针功能显示用户输入的一些数字。但是,输入正常时显示错误。

#include <iostream>
using namespace std;

int main()
{
cout << "How many integers you wish to enter? ";
int InputNums = 0;
cin >> InputNums;

int* pNumbers = new int [InputNums]; // allocate requested integers
int* pCopy = pNumbers;

cout<<"Successfully allocated memory for "<<InputNums<< " integers"<<endl;
for(int Index = 0; Index < InputNums; ++Index)
{
cout << "Enter number "<< Index << ": ";
cin >> *(pNumbers++);
}

cout << "Displaying all numbers input: " << endl;

for(int Index = 0, int* pCopy = pNumbers; Index < InputNums; ++Index) 
    cout << *(pCopy++) << " ";

cout << endl;

// done with using the pointer? release memory
delete[] pNumbers;

return 0;
}

来自(int Index = 0,int * pCopy = pNumbers; Index&lt; InputNums; ++ Index)的行的错误。

实际上来自教科书“在21天内教授c ++”的代码,没有任何改变。

请帮助,非常感谢。

2 个答案:

答案 0 :(得分:1)

你书中的例子很糟糕。它应该是这样的(代码也不好,但这里的代码应该是):

#include <iostream>
using namespace std;

int main()
{
    cout << "How many integers you wish to enter? ";
    int InputNums = 0;
    cin >> InputNums;

    int* pNumbers = new int [InputNums]; // allocate requested integers
    int* pCopy = pNumbers;

    cout<<"Successfully allocated memory for "<<InputNums<< " integers"<<endl;
    for(int Index = 0; Index < InputNums; ++Index)
    {
        cout << "Enter number "<< Index << ": ";
        cin >> *(pCopy++); //use pCopy to 'walk' the array
    }

    cout << "Displaying all numbers input: " << endl;
    pCopy = pNumber; //reset pCopy
    for(int Index = 0; Index < InputNums; ++Index) 
        cout << *(pCopy++) << " ";

    cout << endl;

    // done with using the pointer? release memory
    delete[] pNumbers; //pNumbers must still point to the address returned in line 10

    return 0;
}

我想知道这本书的作者是谁。

答案 1 :(得分:0)

cin >> *(pNumbers++);更改为cin >> *(pCopy++);

int* pCopy = pNumbers更改为*pCopy = pNumbers

这应该可以解决问题。然而,这个例子很丑陋。我建议你改变教科书。