开发者

using ifstream to read in number from a text file into a std::vector<int>

开发者 https://www.devze.com 2023-03-01 02:15 出处:网络
I have a read function which takes numbers from a text file and stored them into a data structure. I have made this function.

I have a read function which takes numbers from a text file and stored them into a data structure. I have made this function.

void VectorIntStorage::read(ifstream &in)
{
    if(in.is_open())
    {
        for (int i = 0; in && i < n; ++ i) 
        {
            in >> vectorStorage<i>;
        }
    }
}

I开发者_开发技巧 am trying to add them into a vector structure, is this code correct??


No, it isn't. The canonical way would be:

vector <int> v;
int n;

while( f >> n ) {
    v.push_back( n );
}

where f is an ifstream.


No, if you write you code this way the compilation will fail. Maybe you can allocate enough space for the vector and then store the date the ifstream read.

vector<int> v(MAX_SIZE);
int iIndex = 0;

while((iIndex < v.size()) && (in >> v[iIndex]))
{
    ++iIndex;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消