How to read a file into vector in C++?

前端 未结 6 1934
执念已碎
执念已碎 2020-12-01 06:34

I need to read from a .data or .txt file containing a new float number on each line into a vector.

I have searched far and wi

6条回答
  •  广开言路
    2020-12-01 07:20

    Just a piece of advice. Instead of writing

    for (int i=0; i=((Main.size())-1); i++) {
       cout << Main[i] << '\n';
    }
    

    as suggested above, write a:

    for (vector::iterator it=Main.begin(); it!=Main.end(); it++) {
       cout << *it << '\n';
    }
    

    to use iterators. If you have C++11 support, you can declare i as auto i=Main.begin() (just a handy shortcut though)

    This avoids the nasty one-position-out-of-bound error caused by leaving out a -1 unintentionally.

提交回复
热议问题