Reading in from a file

I am trying to read in a txt file that contains some doubles as shown below. I have read into it quite a bit and cannot figure out how to get it to read in the file. It is requested that I make an array large enough to hold up to 100 variables. I would just like some input on how to make this work, thanks for your help.
100.8
120.4
121.4
111.9
123.4


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ifstream file("voltages.txt");
	if (file.is_open())
	{
		double myArray[100];
		
		for (int i = 0; i < 100; ++i)
		{
			file >> myArray[i];
		}
	}
	system("Pause");
	return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>

using namespace std;

int main()
{
	ifstream file("voltages.txt");
	if(!file)
	{
		cout << "Could not open input file exiting" << '\n';
		return 1;
	}
	vector<double> myArray(100);
	copy(istream_iterator<double>(file), istream_iterator<double>(), myArray.begin());
	for(const auto elem : myArray)
	{
		cout << elem << '\n';
	}
	cout << "Please enter a character to exit..." << '\n';
	char ch;
	cin >> ch;
	return 0;
}


Don't use system(""); search online to see why.
Avoid arrays, use standard library containers instead.
Last edited on
Hmm. Try outputting the doubles to console, with cout<< or something. You are just writing to the program, not the console. Nest this loop in your for loop:

1
2
3
while(file>>myArray[i]){
cout<<myArray[i]<<endl;
}


Are you trying to output it, or store in something for later use?
I am trying to output it an eventually, output an average. With any number of doubles up to 100.
When I run the program from benbalach, it just outputs a ton of zeros.
You created your array within the scope of an if statement
if (file.is_open()) // note: just 'if ( file )' works too
the array is deleted when it goes out of scope at line 17.
Topic archived. No new replies allowed.