从文件中读取整数到C++中的向量

use*_*063 5 c++ vector

我试图读取存储在从文本文件的单独行中的未知数量的双值到称为的向量rainfall.我的代码不会编译; 我收到了no match for 'operator>>' in 'inputFile >> rainfall'while循环行的错误.我理解如何从一个文件读入一个数组,但我们需要使用矢量这个项目,我没有得到它.我感谢您在下面的部分代码中提供的任何提示.

vector<double> rainfall;    // a vector to hold rainfall data

// open file    
ifstream inputFile("/home/shared/data4.txt");

// test file open   
if (inputFile) {
    int count = 0;      // count number of items in the file

    // read the elements in the file into a vector  
    while ( inputFile >> rainfall ) {
        rainfall.push_back(count);
        ++count;
    }

    // close the file
Run Code Online (Sandbox Code Playgroud)

rcs*_*rcs 10

我认为你应该把它存储在一个类型的变量中double.看起来你正在做>>一个无效的向量.请考虑以下代码:

// open file    
ifstream inputFile("/home/shared/data4.txt");

// test file open   
if (inputFile) {        
    double value;

    // read the elements in the file into a vector  
    while ( inputFile >> value ) {
        rainfall.push_back(value);
    }

// close the file
Run Code Online (Sandbox Code Playgroud)

正如@ legends2k指出的那样,您不需要使用变量count.使用rainfall.size()检索的载体项目的数量.


das*_*ght 10

您不能使用>>运算符来读取整个向量.您需要一次读取一个项目,并将其推入向量:

double v;
while (inputFile >> v) {
    rainfall.push_back(v);
}
Run Code Online (Sandbox Code Playgroud)

您无需计算条目,因为它rainfall.size()会为您提供准确的计数.

最后,大多数C++ -ish读取向量的方法是使用istream迭代器:

// Prepare a pair of iterators to read the data from cin
std::istream_iterator<double> eos;
std::istream_iterator<double> iit(inputFile);
// No loop is necessary, because you can use copy()
std::copy(iit, eos, std::back_inserter(rainfall));
Run Code Online (Sandbox Code Playgroud)


Cha*_*lie 6

你也可以这样做:

#include <algorithm>
#include <iterator>

...
std::istream_iterator<double> input(inputFile);
std::copy(input, std::istream_iterator<double>(),    
          std::back_inserter(rainfall));
...
Run Code Online (Sandbox Code Playgroud)

假设你喜欢STL.


Snp*_*nps 5

输入运算符>>未定义用于将doubles输入到 a 中std::vector

而是std::vector使用两个标记化输入迭代器为输入文件构造。

这是一个示例,说明如何使用2 行代码即可完成此操作:

std::ifstream inputFile{"/home/shared/data4.txt"};
std::vector<double> rainfall{std::istream_iterator<double>{inputFile}, {}};
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是将输入运算符函数定义为:

std::istream& operator>> (std::istream& in, std::vector<double>& v) {
    double d;
    while (in >> d) {
        v.push_back(d);
    }
    return in;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的例子中使用它:

std::vector<double> rainfall;
inputFile >> rainfall;
Run Code Online (Sandbox Code Playgroud)