Alternative implementation of reading the number, which is suitable for different numbers of digits:
number = 0;
// Prepare character buffer to read the number in
char buffer[10] = ""; // space for maximum 9 digits
int pos = 0; // position variable in the buffer
while(fr.available() && pos < 9){ // loop while there is data left to read in the file or we have no pace left in buffer (leaving one character for the terminating null character
char c = fr.read(); // read character into variable
if(isDigit(c)){
buffer[pos] = c; // save digit in buffer
pos++; // increment position for the next character
} else {
break; // break out of loop, if read character is not a digit (we don't want to read further when a non-digit character comes up)
}
}
buffer[pos] = 0; // terminate buffer with null character
number = atoi(buffer); // use standard function to convert to integer number
Note:
- This code is not tested, though it compiles without errors
- You see, that it is not smaller, than the other one, but can handle different number of digits.
- You can still use the first version with smaller numbers, if you always pad them with zeros. So instead
991you would write0991to the file. That will make the first version work.