从文件中单独读取数据并乘以C ++中的两列 [英] Read data from a file individually and multiply the two columns in C++

查看:127
本文介绍了从文件中单独读取数据并乘以C ++中的两列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据文件1.dat,它有4列和250行。



我需要读取每一行并处理它,列[col1和col2]。



您可以建议一种方法吗?



使用C ++。

解决方案

假设文件具有分隔数据,您可能:




  • 使用 ifstream 打开文件

  • 使用 std: :getline(ifstream,line)来读取一行。你可以在一个循环中做到这一点。行应该是 std :: string

  • 使用istringstream(行)处理每行,然后读取这些到你的元素。 li>


要存储读取的数据,可以使用 vector<载体, double> << vector< double>>< vector< >

  ifstream ifs 
std :: vector< std :: vector& double> >垫;
if(ifs.is_open())
{
std :: string line;
while(std :: getline(ifs,line))
{
std :: vector< double>值;
std :: istringstream iss(line);
double val;
while(iss>> val)
{
values.push_back(val);
}
mat.push_back(values);
}
}


I have a data file "1.dat" which has 4 columns and 250 rows.

I need to read each row and process it such as to multiply two columns [col1 and col2].

Can you suggest a way to do this please?

I have to use C++.

解决方案

Assuming the file has delimited data, you will probably:

  • use ifstream to open the file
  • use std::getline( ifstream, line ) to read a line. You can do this in a loop. line should be of type std::string
  • process each line using istringstream( line ) then reading these into your element.

To store the read data you could use vector< vector< double > > or some kind of matrix class.

with vector<vector<double> >

ifstream ifs( filename );
std::vector< std::vector< double > > mat;
if( ifs.is_open() )
{
   std::string line;
   while( std::getline( ifs, line ) )
   {
       std::vector<double> values;
       std::istringstream iss( line );
       double val;
       while( iss >> val )
       {
          values.push_back( val );
       }
       mat.push_back( values );
   }
}

这篇关于从文件中单独读取数据并乘以C ++中的两列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆