I am reading 15 numbers from a text file, with each number in a new line:
1 2 3 4 5 10 12 13 14 15 21 22 23 24 26
As you can see from the code I need the numbers to be validated so they are less than 26, otherwise terminate the program.
At the moment I am validating only after inserting it to the array (numArray). Is there a cleaner way of doing it (to validate before inserting to the array)?
The problem is, I can't seem to get the actual line in the text file that's being read. That's why I've validated it using the loop index on the array (int x = numArray[i];).
Any help is appreciated, I'm quite new to C programming. Thanks.
FILE *myFile = fopen(dataset.txt, "r");
int numArray[15];
if (myFile != NULL) {
for (int i = 0; i < sizeof(numArray); i++)
{
//insert int to array
fscanf(myFile, "%d", &numArray[i]);
//Validate number
int x = numArray[i];
if (x > 25) {
printf("Invalid number found, closing application...");
exit(0);
}
}
//close file
fclose(myFile);
}
else {
//Error opening file
printf("File cannot be opened!");
}
of course you can store it in a local variable and assign only if valid. But since you're calling exit(0)
if invalid it doesn't change anything. I suppose you want to break
from the loop instead.
BTW your loop is wrong. you have to divide sizeof(numArray)
by the size of one element otherwise you'll loop too many times and you'll crash the machine if there are too many numbers in your input file (yes, I also added a test for end-of-file)
if (myFile != NULL) {
for (int i = 0; i < sizeof(numArray)/sizeof(numArray[0]); i++)
{
int x;
//insert int to array
if (fscanf(myFile, "%d", &x)==0)
{
printf("Invalid number found / end of file, closing application...\n");
exit(0); // end of file / not a number: stop
}
//Validate number
if (x > 25) {
printf("Invalid number found, closing application...\n");
exit(0);
}
numArray[i] = x;
}
//close file
fclose(myFile);
}