Hi
I am making a program that reads a text file & displays them into an array.
My problem is; I read the text file to determine how big the array needs to be, then I clear the input from the text file, then I read the text file again & store the text/integers into an array once i know how big the array needs to be. The problem is clearing the input from the text file.
I have used the functions infile.clear(), infile.putback(x), infile.peek() and all of these dont work. Can you tell me how to get infile.clear() to work?
To better understand my problem I have the code below & the contents of the input file(number_list.txt):
#include <iostream>
#include <iomanip>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
int x = 0, y = 0;
int sequence_length = 0;
double number_array[100];
int size = 0;
ifstream infile;
infile.open("number_list.txt");
if (!infile)
{
cout << "Failed to open file";
return 0;
}
// determine the length of the array needed
while(infile) {
infile >> x;
sequence_length++;
}
cout << sequence_length << endl;
// clear the input from infile so we can store x into an array
infile.clear();
// store numbers in an array
for ( int i = 0; i <= sequence_length; i++)
{
infile >> x;
number_array[i] = x;
}
infile.close();
for (int i = 0; i < sequence_length; i++)
{
cout << number_array[i] << ", ";
}
return 0;
}
input file contents:
20 40 45 231 121 45 90 43 -10 -40 -70
sample of my output:
12
-70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70, -70,