> Question about arrays. C++.?

Question about arrays. C++.?

Posted at: 2014-12-18 
Assuming you are using a loop to read the values.

Then after you read a value, test for less than 0 or greater than 100 and if it meets either condition, do a "continue" to skip to the next iteration of the loop.

If it does not meet these conditions, put it in the array, and increment your index, in the last part of the loop.

Problems addressed in this solution:

out of range will be skipped.

invalid values (i.e. a string rather than number) will be ignored.

Problems not addressed int this solution:

a value "45abcd" would be recognized as number (45) and would not be ignored

the value "41.55" would be recognized as number (41), .55 would be ignored

I hope this helps.

#include

#include

#include // for copy in main

using namespace std;

int get_number(const string& strPrompt, const int& ciMin, const int& ciMax, int array[], const int& ciStartIndex = 0, const int& ciArray = 50)

{

int iCount = 0;

string strBuffer;

int iRet = 0;

cout << strPrompt << endl;

getline(cin, strBuffer);

stringstream ss(strBuffer);

iCount = ciStartIndex;

string strError;

while(iCount < ciArray) {

if (ss >> iRet) {

if (iRet >= ciMin && iRet <= ciMax){

array[iCount] = iRet;

++iCount;

}

}

else {

ss.clear();

ss >> strError;

}

if (ss.eof()) break;

}

return iCount;

}

int main()

{

int ar[50] = {0};

int iCount = 0;

while(iCount < 50){

string strBuffer;

stringstream ss;

ss << "Enter " << 50 - iCount << " values (0-100)";

iCount = get_number(ss.str(), 0, 100, ar, iCount);

}

copy(ar, ar + 50, ostream_iterator(cout, " "));

return 0;

}

So I have to enter in up to 50 numbers (0-100) into an array on one line with spaces. If the user enters in a negative number or a number over 100, I'm supposed to skip it and not read it. So far, I can't get it to skip. Anybody have a tips they could pass on to me.

Thanks everyone. Hope it's a good Monday for all.