如何在C++中将文件读入向量?

2021-12-21 00:00:00 file-io vector c++

我需要从 .data.txt 文件中读取每行包含一个新的 float 数字到一个向量中.

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

我已经广泛搜索并应用了许多不同的方法,但每次我得到相同的结果时,Main.size()0 和错误说明向量下标超出范围",所以很明显向量只是没有将任何内容读入文件.

I have searched far and wide and applied numerous different methods but every time I get the same result, of a Main.size() of 0 and an error saying "Vector Subscript out of Range", so evidently the vector is just not reading anything into the file.

注意:该文件既在文件夹中,也包含在 VS 项目中.

Note: the file is both in the folder and also included in the VS project.

无论如何,这是我的代码:

Anyway, here's my code:

#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>

using namespace std;

int main() {

    vector<double> Main;
    int count;
    string lineData;
    double tmp;

    ifstream myfile ("test.data", ios::in);

    double number;  

    myfile >> count;
    for(int i = 0; i < count; i++) {
        myfile >> tmp;
        Main.push_back(tmp);
        cout << count;
    }

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

    cin.get(); 
    return 0;
}

我得到的结果总是很简单:

The result I get is always simply:

Numbers:
0

推荐答案

你的循环错了:

for (int i=0; i=((Main.size())-1); i++) {

试试这个:

for (int i=0; i < Main.size(); i++) {

此外,将数字读入向量并将它们写入标准输出的更惯用的方法是:

Also, a more idiomatic way of reading numbers into a vector and writing them to stdout is something along these lines:

#include <iostream>
#include <iterator>
#include <fstream>
#include <vector>
#include <algorithm> // for std::copy

int main()
{
  std::ifstream is("numbers.txt");
  std::istream_iterator<double> start(is), end;
  std::vector<double> numbers(start, end);
  std::cout << "Read " << numbers.size() << " numbers" << std::endl;

  // print the numbers to stdout
  std::cout << "numbers read in:
";
  std::copy(numbers.begin(), numbers.end(), 
            std::ostream_iterator<double>(std::cout, " "));
  std::cout << std::endl;

}

尽管您应该检查 ifstream 的状态是否有读取错误.

although you should check the status of the ifstream for read errors.

相关文章