将输入文件读入矢量

时间:2016-04-27 01:45:00

标签: c++

我正在尝试将intdouble的文件读入矢量,但我很难这样做。给出类似的东西:

1 2.1 3 4
2 4 
3
9 0.1

如何使用ifstreamgetline函数将字符串转换为整数和双精度数字&将其插入矢量?

我知道这是不正确的,但我想的是:

vector<Pair *> vec; //Pair is a class that contains a int & a double data member
string str;
double num;
ifstream f;
f.open("name of file");
while(getline(f, str){
  num = stod(str);
}

要插入载体,我相信我可以按照以下方式做一些事情:

Pair * pairObj = new Pair(x,y); //"x" being of type int and "y" being of type double
v.push_back(pair);

如果不清楚我很抱歉,请告诉我,我会尽力解释自己。

3 个答案:

答案 0 :(得分:0)

strtod()是C.正确的C ++使用>>运算符。

读完每一行文本后,从字符串构造std::istringstream,然后使用operator>>对其进行解析。

沿着这条线的东西::

std::ifstream f("name of file");

// Check if the file was succesfully opened, etc...

std::string str;

while( getline(f, str))
{
    std::istringstream i(str);
    std::vector<double> v;
    double d;

    while (i >> d)
    {
        v.push_back(d);
    }

    if (!i.eof())
    {
        // Must be a parsing failure, deal with it in some way.
    }
    else
    {
       // Otherwise, v is the vector of numbers on this line.
    }
}

答案 1 :(得分:0)

string str;
std::vector< double> vd;
// loop reading lines of input
while( getline( f, str )
{
std::stringstream sst(str);
std::string a;
// loop reading space separated values in line
while( getline( sst, a, ' ' ) )
    // conver to double and add to end of vectior
    vd.push_back( stod( a );
}
// check for complete pairs
if( vd.size() % 2 )
    cout << "Error!"
// loop over pairs
vector< pair<int,double> > vpairs;
for( int kp = 0; kp < vd.size()/2; kp++ )
    vpairs.push_back( pair<int,double>( (int)vd[kp*2],vd[kp*2+1) ); 

答案 2 :(得分:0)

你应该只使用流迭代器!

#include <iostream> // for IO
#include <vector> // for vector!
#include <iterator> // for stream iterator
#include <algorithm> // for copy (optional) 

如果您正在直接初始化

vector<double>vdata{istream_iterator<double>(ifile), 
                    istream_iterator<double>()};  

如果您只需要固定数量的数据,则使用copy或copy_n

copy(istream_iterator<double>(ifile), 
     istream_iterator<double(),
     back_inserter(vdata)); 

如果您正在处理大文件,我建议您使用此方法

vector<doube>vdata;
// this will save alot of time, if you don't resize the vector must keep reallocating data
vdata.reserve(file_size);
copy(istream_iterator<double>(ifile), 
     istream_iterator<double>(),
     back_inserter(vdata));