Writing from file to array

Hello,
I need to write from a file to an array. The data in the file is stored as two numbers separated by spaces (tabs). I am having trouble populating the array, but receive no errors so I'm not sure what the deal is. For pieces of the code will Thanks in advance!

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
 #include <iostream>
#include <fstream>
#include <cmath>
#include <string>

using namespace std;


int main()
{
ifstream inputweather;
inputweather.open ("project4.txt");
int linecounter = 0;

if(!inputweather.fail())

{	
	string line;
	cout << "The file opened, preparing the menu" << endl;
		
	while (inputweather.good())
	{
		linecounter ++;
	}
	char weatherarray[linecounter];
	cout << "Step 1 complete" << endl;
	
	while (inputweather.good())
	{
	int position = 0;
	inputweather >> weatherarray[position];
	position ++;
	}
}
else 
{
	cout << "The file failed to open" << endl;
	
}
return 0;
}
Last edited on
If you know the size of the file, then it will be easy. Just set the size of the array to the number of positions you need for all of the numbers in the file.

then:

1
2
3
4
5
6
7
8
9
10
int SIZE = ?; // Whatever size you need for your array
int myArray[SIZE]; // Creating array
int i = 0; // Initialize iterator
string line;

while(getline(fileName, line) // Getting lines as strings
 {
   myArray[i]=stoi(line); // Putting 'line' into array after string to integer conversion
   i++;
 }
This is an infinite loop.
1
2
3
4
	while (inputweather.good())
	{
		linecounter ++;
	}



This is illegal it would have to be a dynamic array.
char weatherarray[linecounter];
Last edited on
Thank you for the quick replies!
Unfortunately, stoi does not work (compiler is out of date I guess?).
Yanson, thanks for the tip.
Nah, stoi seems to not be an ANSI standard.

You can always use a stringstream to convert.
Topic archived. No new replies allowed.