transfering inputFile to vector c++

Feb 5, 2017 at 6:24am
We're supposed to Write a program that reads an unknown number of integers from a data file called “data.txt” into a vector of integers named V. V is initially empty and grows as the user reads data from file.

Once done copying data into vector V, you need to print the contents of V (write a function print that prints the contents of a vector of any size) and perform some other tasks on the vector as described below.

This is the data file: 5 6 12 87 100 28 35 66 77 29
EVERY TIME I RUN THIS CODE IT OUTPUTS: 5 12 100 35 77

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
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int main()
{
  vector <int> v;
  int count;
  int tmp;

    ifstream inputFile;
    inputFile.open("data3.txt");

    if(!inputFile)
      {

        cout << "File does not exist";
      }

    else
      {
        while (inputFile >> count)

          {
            cout << count <<" ";
            v.push_back(count) ;
            inputFile >> count;
          }
        inputFile.close();

      }


    return 0;
}

Feb 5, 2017 at 6:34am
1
2
3
4
5
6
7
        while (inputFile >> count)

          {
            cout << count <<" ";
            v.push_back(count) ;
            inputFile >> count;
          }

You're reading twice but outputting once, which explains why the output skips every other number. Simply remove the line in question and it will work as expected.
Last edited on Feb 5, 2017 at 6:35am
Feb 5, 2017 at 7:44am
Thanks it worked !
Topic archived. No new replies allowed.