> C++ arrays. please help!?

C++ arrays. please help!?

Posted at: 2014-12-18 
Additionally to your request this code provides a function called get_number. The reason why I provided it is that in case you enter i.e. a character like a - z or A-Z on the command input, you will run into an endless loop.

As Jeff mentioned, your code is good with respect to allocating memory for an int array. It does not assign any numbers to the array, which int this very case I actually find unnecessary. Instead of doing the memory allocation, your code could just ask for the printer number and then without any allocation could do the following:

for (int i = 0; i < p; i++) {

cout << " p" << i + 1;

}

This would result in the output, you requested. The following code uses an array, assigns the values as shown above and displays them. Unlike your code the allocated memory is freed after usage. Have fun ...

#include

#include

using namespace std;

int get_number(const string& strPrompt, const int& iMin, const int& iMax)

{

int iRet = 0;

string strBuffer;

do {

cout << strPrompt << "> ";

getline(cin, strBuffer);

stringstream ss(strBuffer);

if (ss >> iRet){

if (iRet < iMin || iRet > iMax) {

cout << "Range: " << iMin << " <= x <= " << iMax << endl;

}

else

break;

}

} while(true);

return iRet;

}



int main()

{

int *pArray;

int p = get_number("Please enter the number of printers: ", 1, 99);

pArray = new int[p];

for (int i = 0; i < p; i++) {

pArray[i] = i + 1;

}

for (int i = 0; i < p; i++){

cout << " p" << pArray[i];

}

delete [] pArray;

}

What you're doing is fine to create an array with length p

You have to understand though that your are trying to get the values at those positions and they simply haven't been assigned yet...

If I put in 3 I have an array (pArray) with a size of 3 but pArray[0], pArray[1], pArray[2] are undefined until they are assigned values. Outputting them only gives you garbage.

Someone please help so like if user enters 2 for the value of p, it needs to output p1 p2. If enters 3 for the value of p, it needs to output p1 p2 p3. How to do this? Please help! I need to use array.

int *pArray;

int p;

cout<
cin>>p;

pArray = new int[p];

for (int i = 0; i > p; i++){

cout << "p" << pArray[i];

}