将数据文件读入2d数组c ++

时间:2013-01-30 09:25:49

标签: c++ multidimensional-array

我有一个包含2列和多行的文本文件。每列用空格分隔。我需要将它们读取到2D阵列以进行进一步计算。 我的数据文件看起来像

0.5 0.479425539
1   0.841470985
1.5 0.997494987
2   0.909297427
2.5 0.598472144
3   0.141120008
3.5 -0.350783228
4   -0.756802495
4.5 -0.977530118
5   -0.958924275  

我的微弱尝试是

#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>
#include <ctype.h>
using namespace std;

int main () {
  char line,element;
  std::ifstream myfile ("C:\\Users\\g\\Desktop\\test.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline(myfile,line);
       cout << line<<endl;               
      _getch();
    }
    myfile.close();

  }

  else cout << "Unable to open file"; 

  return 0;

}

问题是我无法正确读取它......它要么读取整行......如果我将分隔符指定为'空格',那么它不会读取下一行。

请指出什么是错的。以及如何将数据存储到2d数组以进行进一步计算。 谢谢

3 个答案:

答案 0 :(得分:1)

您可以将整行读入std::string,然后使用std::istringstream从该行中提取值。


完整的工作计划:

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

int main()
{
    std::ifstream file("C:\\Users\\g\\Desktop\\test.txt");

    std::string line;

    // Read a line of input from the file
    while (std::getline(file, line))
    {
        // `istringstream` behaves like a normal input stream
        // but can be initialized from a string
        std::istringstream iss(line);

        float value;

        // The input operator `>>` returns the stream
        // And streams can be used as a boolean value
        // A stream is "true" as long as everything is okay
        while (iss >> value)
        {
            std::cout << "Value = " << value << '\t';
        }

        // Flush the standard output stream and print a newline
        std::cout << std::endl;
    }
}

如果文件中的内容与问题中的内容相同,则前三行输出应为:

Value = 0.5 Value = 0.479425539
Value = 1   Value = 0.841470985
Value = 1.5 Value = 0.997494987

对于二维数组,我会使用std::vectorstd::array

#include <vector>
#include <array>

...

std::vector<std::array<float, 2>> array;

...

float value1, value2;
if (iss >> value1 >> value2)
{
    std::cout << "Values = " << value1 << ", " << value2;

    array.emplace_back(std::array<int, 2>{{value1, value2}});
}

现在第一行的值为array[0][0]array[0][1],最后一行的值为array[array.size() - 1][0]array[array.size() - 1][1]

答案 1 :(得分:1)

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

int main(int argc, char** argv) {
   std::ifstream f(argv[1]);
   std::string l;
   std::vector<std::vector<double> > rows;
   while(std::getline(f, l)) {
       std::stringstream s(l);
       double d1;
       double d2;
       if(s >> d1 >> d2) {
           std::vector<double> row;
            row.push_back(d1);
            row.push_back(d2);
            rows.push_back(row);
        }
    }

    for(int i = 0; i < rows.size(); ++i)
        std::cout << rows[i][0] << " " << rows[i][1] << '\n';
}

最后一个for循环显示了如何使用“数组”中的值。严格来说,变量行不是数组,而是矢量矢量。但是,向量比c样式数组更安全,并允许使用[]。

访问其元素

[我发布此消息后,我看到一个非常类似的程序作为回复发布。我独立写了我的。]

答案 2 :(得分:0)

随着C ++多年来的发展,以下是现代C ++版本。

  • 尽可能使用auto
  • 使用std :: pair来保存2个值(std :: pair是带有两个元素的std :: tuple的特定情况)
  • 不关闭文件(析构函数在块结束时执行此操作)
  • 不逐行阅读,因为流使用&lt; space&gt;和&lt; enter&gt; as delimiters
  • 变量具有有意义的名称,因此程序&#34;读取&#34;容易,
  • 使用范围for循环输出数据。
  • 没有将整个std命名空间带入代码 - Why is “using namespace std” considered bad practice?

#include <fstream>
#include <iostream>
#include <vector>
#include <utility>

int main( int argc, char** argv )
{
    if ( argc < 1 )
        return -1;

    const auto    fileName = argv[ 1 ];
    std::ifstream fileToRead( fileName );

    typedef std::pair< double, double > DoublesPair;
    std::vector< DoublesPair > rowsOfDoublesPair;
    DoublesPair                doublePairFromFile;

    while ( fileToRead >> doublePairFromFile.first >> doublePairFromFile.second )
    {
        rowsOfDoublesPair.push_back( doublePairFromFile );
    }

    for ( const auto row : rowsOfDoublesPair )
        std::cout << row.first << " " << row.second << '\n';
}
相关问题