I need to read integers from a text file into a two-dimensional array.
-1 indicates the end of array. Every array supposes to have 6 positive integers (-1 does NOT count as part of the array).
For example, if my text file contains the following integers:
1 3 4 6 1 7 -1 1 3 5 7 2 3 -1 2 5 7 2 6 3 -1
That means when these integers are read into the program, there will be 3 arrays:
1st Array: 1 3 4 6 1 7
2nd Array: 1 3 5 7 2 3
3rd Array: 2 5 7 2 6 3
I wrote a program to assess if each array has a correct length (6 integers) AND correct integers (all integers should be positive) and output corresponding error messages if these criteria are not met.
#include <iostream>
#include <fstream>
#include <string>
#define MAX_ROWS 3
#define MAX_COLUMNS 2
using namespace std;
int main()
{
string fileName = "testdata.txt"; //declare a string to store the Input File's name
ifstream inFile; //name the input file connection
inFile.open(fileName); //open the Input File
string errorMessage = "Input file cannot be found"; //Declare a string to store an error message, just in case the Input file doesn't exist or cannot be found
if (!inFile) { //If the Input File doesn't not exist, then display the error message
cout << errorMessage << '\n'; //also store the error message to the Output file
system("pause");
return 0; //end the program if the Input File does not exist
}
int checkNbr;
int ArrB[MAX_ROWS][MAX_COLUMNS];
int size = MAX_ROWS * MAX_COLUMNS;
bool bad = false;
bool invalidnum = false;
while (!inFile.eof())
{
for (int i = 0; i < MAX_ROWS;i++) {
for (int j = 0; j < MAX_COLUMNS; j++) {
inFile >> ArrB[i][j];
if (ArrB[i][j] == -1) {
bad = true;
cout << "\nThe array does not have enough integers" << endl;
break;
//return 1;
}
else {
if (ArrB[i][j] < 1) {
invalidnum = true;
}
}
cout << *(*(ArrB + i) + j) << " ";
}
}
if (invalidnum == true) {
invalidnum = false;
cout << "\nThere is/are negative number(s) or zero(s) in the array imported from your text file.\n";
}
if (bad == false) {
inFile >> checkNbr;
if (checkNbr == -1) {
cout << "\nThe size of the array is correct." << endl;
}
else {
while (checkNbr != -1)
{
cout << checkNbr;
cout << " ";
inFile >> checkNbr;
}
cout << "\nYou have too many numbers in this array\n";
}
}
}
return 0;
}
If I run my program:
Case 1 - PASSED
1 2 3 4 5 6 -1 3 5 2 1 6 8 3 2 5 -1 3 3 5 6 7 5 -1
Case 2 – PASSED
1 2 3 4 5 -6 -1 3 -5 2 1 6 8 -1 3 5 6 7 5 -1
Case 3 – FAILED(!)
1 2 3 4 -1 1 2 3 4 5 6 7 8 -1 1 2 3 4 5 -1
As you can see, case 3 failed. The second array (1 2 3 4 5 6 7 8) is actually longer than the declared array size, but it’s printing out “The array does not have enough integers” error message…..
The ONLY time this program won't work is when the first array does not have enough integers.
Any comments or hints would be appreciated!