如何使用C ++逐行读取由双值组成的文件

how to read in files made of double values line by line using c++

我正在尝试做一些非常简单的事情,但就是做不好... 使用 C++,我想读入 "myfile.tsv",它看起来像这样:

2.3 3.3 3.4 3.5 5.6 \n 1.2 1.3 1.2 \n 3.4 3.5 3.5 \n 4.4 4.6 1.3 1.5 \n ...

多行双精度值,每行可能有不同的大小。

我想逐行读入,并将每一行放入一个 vector<double>,最后将所有的值保存在一个vector<vector<double>>.

提前感谢任何提示~

使用 getline 和 stringstream

while(getline(file,str)){
   stringstream stream(str);
   double something;
   while(stream>>something){
       //Push it into inner vector<double>
   }
   //push vector<double> into vector<vector<double> > here
}

你可以自己算出里面的细节。

我已经使用 stringstringstream 来模拟您的文件。 下面是代码

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

int main() {
    // your code goes here
    string str = "2.3 3.3 3.4 3.5 5.6 \n 1.2 1.3 1.2 \n 3.4 3.5 3.5 \n 4.4 4.6 1.3 1.5 \n";
    stringstream ss(str);
    double temp = 0.0; 
    vector<vector<double>> vec1;
    string s;
    while(getline(ss,s,'\n'))
    {
        cout<<s<<endl;
        vector<double> vec;
        stringstream ireadString(s);
        while(ireadString>>temp)
        {
            vec.push_back(temp);
        }
        vec1.push_back(vec);
    }
    vector<vector<double>>::iterator itr = vec1.begin();
    for (; itr != vec1.end() ; itr++)
    {
        vector<double> v = *itr;
        for (vector<double>::iterator itr1 = v.begin(); itr1 != v.end() ; itr1++)
            cout<<*itr1<<'\t';
    }
    return 0;
}

这里显示了如何完成

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

int main() 
{
    std::ifstream if( "input.txt" );

    std::vector<std::vector<double>> v;

    std::string line;

    while ( std::getline( if, line ) )
    {   
        std::istringstream is( line );
        v.emplace_back( std::vector<double>( std::istream_iterator<double>( is ), 
                                             std::istream_iterator<double>() ) ); 
    }        

    for ( const auto &row : v )
    {
        for ( double x : row ) std::cout << x << ' ';
        std::cout << std::endl;
    }
}    

如果文件包含以下数据

2.3 3.3 3.4 3.5 5.6 \n 1.2 1.3 1.2 \n 3.4 3.5 3.5 \n 4.4 4.6 1.3 1.5 \n

那么输出将是

2.3 3.3 3.4 3.5 5.6 
1.2 1.3 1.2 
3.4 3.5 3.5 
4.4 4.6 1.3 1.5