putting data into an array using a for loop from input file

Hi there, I'm trying to pass several integers into the array idAr[10] from an input file using a for loop and then having them output on the console. The output should look like this:
1001
1002
1005
1007
1010
1009
1003
1008
1004
1006


Can someone please point to what I'm doing wrong? Thanks

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
#include <iostream>
#include <fstream>
using namespace std;


int main()
{

        ifstream inputFile;

 	int index;

	int idAr[10];

	inputFile.open("inFile.txt");

	 for(index = 0; index < 10; ++index);
 	{
		inputFile >> idAr[index];
	}

	inputFile.close();

	cout << idAr[0] << endl << idAr[1] << endl
	     << idAr[2] << endl << idAr[3] << endl
	     << idAr[4] << endl << idAr[5] << endl
             << idAr[6] << endl << idAr[7] << endl
	     << idAr[8] << endl << idAr[9];


	return 0;

}
Last edited on
It looks okay to me. What error message are you getting?
-277251416
32738
-279341034
32738
1
0
-1645526448
32767
-288707288
32738

the output looks like that, but its supposed to look like this
1001
1002
1005
1007
1010
1009
1003
1008
1004
1006
There is a semicolon after your for loop.

Also, after every read operation, you should check whether the read was successful.

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
#include <iostream>
#include <fstream>
using namespace std;


int main()
{

        ifstream inputFile;

 	int index = 0;

	int idAr[10];

	inputFile.open("inFile.txt");

        // A while loop seems more natural to me here, but you can stay with for loop also.
	while ( index < 10 && inputFile >> idAr[index] )
 	{
              ++index;
	}

	inputFile.close();

       if ( index < 10 )
       {
              cout << "Error! All values not read\n";
              exit(1);
       }

	cout << idAr[0] << endl << idAr[1] << endl
	     << idAr[2] << endl << idAr[3] << endl
	     << idAr[4] << endl << idAr[5] << endl
             << idAr[6] << endl << idAr[7] << endl
	     << idAr[8] << endl << idAr[9];


	return 0;

}


Last edited on
oh I think I get how your code works, ill need to test it and thanks gotta stop coding while stonned
Topic archived. No new replies allowed.