Reading numbers from a file

Hi, I'm trying to read some numbers from a file called numbers.txt. There are 10 numbers in this file in this kind of format:

numbers.txt
1
2
3
4
5
6
7
8
9
10
87
89
91
93
95
97
99
101
103
105


Once I read these numbers from the file I want to store them in an array of size 10. However, when I do a cout statement to see the contents of my array I'm noticing the first element is not being read and the last element is being repeated twice. I really don't know why that is the case.

Any help would be greatly appreciated thank you!


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

void readFromFileArray() {
    array<int, 10> numbersFile;
    fstream intFile("numbers.txt");

    if (!intFile) {
        throw runtime_error("Could not locate the file");
    }

    int tmpInt;


    while (intFile >> tmpInt) {
        for (int i = 0; i < numbersFile.size(); i++) {
            intFile >> tmpInt;
            numbersFile[i] = tmpInt;

        }

    } 


   for (int i = 0; i < numbersFile.size(); i++) {
        cout << numbersFile[i] << endl;
    } 
}


int main(){

    readFromFileArray();
}


So for example the current console output looks like this:
89
91
93
95
97
99
101
103
105
105

When it should be this:
87
89
91
93
95
97
99
101
103
105


Last edited on
Replace the whole of your while loop and accompanying lines (i.e lines 16-24) with the single line
for (int i = 0; i < numbersFile.size(); i++) intFile >> numbersFile[i];
Last edited on
@lastchance Thank you so much! I was just wondering what exactly was the logical error I made in order to get the incorrect output in the first place?
bobcat854 wrote:
I was just wondering what exactly was the logical error I made in order to get the incorrect output in the first place?



The first item in your file was read with the statement
while (intFile >> tmpInt)
but you didn't do anything with this input.


You then tried to read 10 more items, but there were only 9 more left in the file, so the last read would have failed. You would then end up assigning the last correctly read item in tmpInt for a second time to the last element of numbersFile[].
Topic archived. No new replies allowed.