Reputation: 3
I need to store an array of integers from a text file, but I can't find what I need to do for it exactly. I think I have the basis of the code set up, but I think I need to convert the elements into integers or something?
My output is my list :
50 0 20 10 18 -5 15 22 34 -1
But my "sorted" list ends up being -1, and a series of large negative numbers. I troubleshooted it to being something wrong with the array.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array1[30];
int counter=0,n=0;
fstream datafile;
void bubbleSort(int list[], int length);
void selectionSort(int list[], int length);
/////////////
datafile.open("data.txt");
if (!datafile.is_open())
{
cout << "Failure to open." << endl;
return 0;
}
while (!datafile.eof()) {
datafile >> array1[counter];
n++;
cout << array1[counter] << endl;
}
datafile.close();
//////////////////////////////
//bubbleSort(array1, n);
//selectionSort(array1, n);
for (int i = 0; i < n; i++)
cout << array1[i] << ", ";
system("pause");
return 0;
}
Upvotes: 0
Views: 1001
Reputation: 28199
Your code is all good except :
while (!datafile.eof()) {
datafile >> array1[counter];
n++;
cout << array1[counter] << endl;
}
It should be:
while (!datafile.eof()) {
datafile >> array1[n];
if ( datafile.fail() ) break;
cout << array1[n] << endl;
n++;
}
Only a single index variable(n
) is required to parse/store into a 1D array.
The increment statement n++
in a while should always be the last one so that you are working on the current element and not the next.
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array1[30];
int n=0;
fstream datafile;
void bubbleSort(int list[], int length);
void selectionSort(int list[], int length);
/////////////
datafile.open("data.txt");
if (!datafile.is_open())
{
cout << "Failure to open." << endl;
return 0;
}
while (!datafile.eof()) {
datafile >> array1[n];
if (datafile.fail()) break;
cout << array1[n] << endl;
n++;
}
datafile.close();
for (int i = 0; i < n; i++)
cout << array1[i] << ", ";
system("pause");
return 0;
}
Upvotes: 0
Reputation: 41617
Never use eof()
, since it leads to wrong programs. See https://stackoverflow.com/a/5837670 for the reason.
while (n < 30 && datafile >> array1[n]) {
cout << array1[n] << endl;
n++;
}
{
int excess;
if (datafile >> excess) {
cerr << "error: data file too large\n";
return;
}
}
That way, the n
will be correct at the end of the program.
Upvotes: 1