#include <iostream>;
#include <fstream>
#include <iomanip>;
using namespace std;
int main() {
// Create Text File to store the Values
const int ARRAY_SIZE = 10;
int numbers[ARRAY_SIZE] = { 5, 10, 8, 7, 3, 4, 9, 6, 2, 1 };
int store_count;
ofstream outputFile;
outputFile.open("TenNumbers.txt");
for (store_count = 0; store_count < ARRAY_SIZE; store_count ) {
outputFile << numbers[store_count] << endl;
}
outputFile.close();
int count = 0;
int num_row1[5];
int num_row2[5];
int nums_array[2][5];
ifstream inputFile;
inputFile.open("TenNumbers.txt");
while (count < 5 && inputFile >> num_row1[count])
cout << num_row1[count] << endl;
// Store value into 2d Array
count ;
while (count < 10 && inputFile >> num_row2[count])
cout << num_row2[count] << endl;
// Store value into 2d Array
count ;
inputFile.close();
cout << endl;
return 0;
};
This is the Output for the File it is reading and the Array that is producing the error:
This is the file numbers that need to be in the 2d array 5 10 8 7 3 4 9 6 2 1
This is what the 2d array shows 1 -858993460 -858993460 -858993460 -858993460
CodePudding user response:
Your error almost certainly resides in this type of code.
while (count < 5 && inputFile >> num_row1[count])
cout << num_row1[count] << endl;
// Store value into 2d Array
count ;
If we indent this more correctly, we get:
while (count < 5 && inputFile >> num_row1[count])
cout << num_row1[count] << endl;
// Store value into 2d Array
count ;
The count ;
statement is not within the while loop, so count
never changes. This means you're never filling more than one element in your array, and the rest are uninitialized, which means their contents are undefined.
You probably meant to write:
while (count < 5 && inputFile >> num_row1[count]) {
cout << num_row1[count] << endl;
// Store value into 2d Array
count ;
}
CodePudding user response:
Firstly, you don't need ;
after #include <...>
because #include <...>
is not a statement. The ;
after it is just evaluated into a null statement.
Also
while (count < 5 && inputFile >> num_row1[count])
cout << num_row1[count] << endl;
// Store value into 2d Array
count ;
while (count < 10 && inputFile >> num_row2[count])
cout << num_row2[count] << endl;
// Store value into 2d Array
count ;
I think that you meant this:
while (count1 < 5 && inputFile >> num_row1[count1])
{
std::cout << num_row1[count1] << std::endl; // change to different variable names
// Store value into 2d Array
count ;
while (count2 < 10 && inputFile >> num_row2[count])
{
std::cout << num_row2[count2] << std::endl;
// Store value into 2d Array
count ;
} // block scope with proper indentation
}