//Reads in digits for an array.
int getFactors (int ary[], ifstream &inFile)
{
char k = '0';
int count;
for (int i = 0; i < MAX; i++)
{
while (k != '\n')
{
count++;
inFile >> k;
ary[i] = k - '0'; //Convert character to integer and store in array.
cout << ary[i]; //TEST
}
}
return count;
}
I have this function which is intended to read input from a file one character at a time and convert and store the integers in an array. When I run this with the //TEST part that you see below, I get an infinite loop that looks like this:
constint MAX = 100 ;
int getFactors( int ary[], std::istream& stm )
{
char k = '0';
int count = 0 ; // initialise
while( stm.get(k) && // a character was read ( note: stm >> k skips whitespace; it won't read a new line)
k != '\n' && // and it was not a newline
count < MAX ) // and the array bound is not exceeded
{
if( k >= '0' && k <= '9' ) // isdigit : if it is a digit
{
ary[count] = k - '0'; // Convert character to integer and store in array.
++count ;
}
else { /* the character is not a digit. throw it away(?) */ }
}
return count;
}
Thanks @JLBorges, that was helpful and I modified my code using your suggestions. I'm having a weird thing happening now though. As the program steps through the input file, when it encounters a number that takes up the entire array (30 integers) it goes back and gets the number before that one before moving on the next one..?
void printUnEArray (int ary[])
{
for (int i = 0; i < MAX; i++)
{
cout << ary[i];
}
}
Note: The reason I am printing out all the way to MAX instead of the exact number of elements in the array has to do with the purpose of other parts of the program.
int getFactors (int ary[], std::ifstream &inFile)
{
char k = '0';
int count = 0;
// initialise the array to all zeroes
for( int i = 0 ; i < MAX ; ++i ) ary[i] = 0 ; // *** added ****
while (inFile.get(k) && k != '\n' && count < MAX)
{
if (k >= '0' && k <= '9')
{
ary[count] = k - '0';
count++;
}
}
// ******************* added ***********************
if( k != '\n' ) // if there are more characters left in this particular line
inFile.ignore( 1000000, '\n' ) ; // throw them away
// http://www.cplusplus.com/reference/istream/istream/ignore/return count;
}