Hello,

This is my first time using vectors. The code below creates a vector of size 30, but when I run the program (which loads 30 integers into the vector), the last integer in my data.txt file does not load into the vector.

When I use a vector of size 31 it works fine. I am just curious why it does not work with 30. My data file has 30 integers, 0-29.

#include "utility.h"
#include "lnklist.h"
#include <vector>


int main()
{
    int number;
    int i = 0;
    int array[29];                              //declare an array of type int with size 30.
    vector<int> vectorOne(29);                  //declare a vector of type int with size 30.

//=======================================================
    ifstream in_stream;
    in_stream.open("data.txt");
    if(in_stream.fail( ))
    {
      cout << "unable to find input file";      //displays error message if file is not found
      exit(1);                                  //exits the program if file is not found
    }//end if in_stream.fail( )
//=======================================================

    while (in_stream >> number)     //in_stream >> number returns a Boolean value of true if the operation has been successful.
    {
        //array[i] = number;
        //cout << array[i] << endl;       //test array in feed

        vectorOne.at(i) = number;
        cout << vectorOne.at(i) << endl;

        i++;
    }

    cout << "Done!" << endl;
    return 0;
}

>> vector<int> vectorOne(29);

The array on line 10 and the vector only have 29 items, not 30. If you want 30 then say so. Count them on your fingers if you need to verify, 0, 1, 2, 3, ... 29, 30.

When you declare an array or a vector you don't subtract one from the size when you declare it.

int foo[30];  // creates a array of size 30 indexed from 0-29
vector<int> bar(30);  // creates a vector of size 30 indexed from 0-29

if you do

int foo[29];  // creates a array of size 29 indexed from 0-28
vector<int> bar(29);  // creates a vector of size 29 indexed from 0-28

@Ancient Dragon 0,1,2...29,30 counted up is 31

commented: good catch :) +17
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.