Help with txt file to array

Hello, Im trying to pass values in the txt file to my array. But my program is not able to do that. It gets an error about break or something like that. I would like to know how to fix this.

The numbers in the txt file are : 44 56 7 8



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
43
44
45
46
#include<cmath>
#include<string>

#include<iostream>
#include<fstream>
using namespace std;

int main ()
{
	int n; // number read from file
	int list[5];

	ifstream inFile; // the input file

	inFile.open("number.txt");

// Exit if there was an error
    // opening the file
	if (!inFile)
	{
		cout << "Error opening input" << endl;
		return -1;
	}
    
    // Loop through the input file
	while ( !inFile.eof() )
	{
		inFile>> n;
		for(int i = 0; i <= 4; i++)
		{
			list[n];
		}



	}
    // close the input file
	inFile.close();
  
    
    
	cout<<list[2]; // the number i want to output
    
    system("pause");
    return 0;
}

Last edited on
while(!inFile.eof()) is usually wrong. I don't think you actually need it because you are already using a for loop. You should put inFile>> n; inside the for loop or otherwise all the array elements will be set to the same value.
I did what you saud Peter and it got worse :(
Trying not to change your code so much, there's one option:

int n will no longer serve as an intermediate, it will the iterator for entering each int of the array. first time, you assign the first number of you file to list[0], second time to list[1], and so on...

obviously, as pointed by peter, you had a problem with your loops, I suggest you get rid of the "for" one.

1
2
3
4
5
6
7
n=0;    // To refer each block of the array
while ( !inFile.eof() )
{
inFile>> list[n]; //assigning the content of the block of the array 
n++; //increasing each time by 1
}


What I'm not sure is how actually works the >> operator, don't know if it will stop after each blank space, or else...? I think it's way better to use getline, strings and stringstream, but nevermind...
Last edited on
Thanx JCaselles it works now!!
Topic archived. No new replies allowed.