c++ - 从文本文件中读取矩阵并在 C++ 中使用一列的数字

标签 c++

我是初学者 我正在使用 CORSIKA 软件。 cosika 的输出是具有 8 或 7 列和超过 2000 行(如矩阵)的文本文件。 该矩阵的数组是科学计数法中的数字,如休闲图像

2.11285E+05  2.00000E+01  1.30714E+05  7.35000E+00  1.00000E+00  1.10000E+04  0.00000E+00
0.00000E+00  0.00000E+00  0.00000E+00  0.00000E+00  0.00000E+00  0.00000E+00  0.00000E+00
0.00000E+00 -2.70000E+00  1.00000E+03  1.00000E+03  1.00000E+00  1.00000E+00  3.00000E-01
3.00000E-01  3.00000E-03  3.00000E-03  6.37132E+08  6.00000E+05  2.00000E+06  0.00000E+00
0.00000E+00  4.58060E-02  5.73090E-01  5.28304E-02  2.50000E+00  2.07000E+00  8.20000E+00
1.00000E-01  0.00000E+00  0.00000E+00  1.00002E+00  9.67266E-03  1.00000E+00  5.75129E-04
0.00000E+00  0.00000E+00  3.77000E+01  1.53287E-04  9.38642E+00  2.00000E-03  2.99792E+10

我想读取第 7 列的数据并计算一些参数,例如一列中的平均值、最大值、最小值。

我有这段代码可以读取和显示文本文件,但我不知道如何使用数字和计算一些参数。

#include<iostream.h>        
#include<stdio.h>
#include<conio.h>

int main()
{
    FILE *k;
    char c;
    k = fopen("c:\\fff.txt", "r");
    c = getc(k);
    while(c != EOF)
    {
         cout << c;
         c = getc(k);
    }
    getch();
    fclose(k);
    return 0;
}

请帮帮我。 谢谢

最佳答案

试试这个:

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

int main()
{
    std::string line;
    std::istringstream iss;

    while (std::getline(file >> std::ws, line))
    {
        float f;

        iss.str(line);
        while (iss >> f)
            ;

        // f is equal to the 7th row by this line
    }
}

根据您的需要,f 可以是 while 循环或其他范围的局部。

关于c++ - 从文本文件中读取矩阵并在 C++ 中使用一列的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19834245/

相关文章:

c++ - 从另一个类设置只读属性

c++ - 跨平台格式字符串

c++ - 计算小数点后的数字 C++

c++ - int lastIndex [NO_OF_CHARS] = {-1}如何;与vector <int> lastIndex(NO_OF_CHARS,-1);不同吗?

c++ - 有没有比添加 0.5f 和截断转换更直接的方法来将 float 转换为 int 并进行舍入?

c++ - 静态库

c++ - 在 C++ 中逐行读取 const 数据

c++ - 在编译时检索 Opencv Mat_<T> 的类型

c++ - `=default` move 构造函数是否等同于成员 move 构造函数?

c++ - makefile 未定义对已定义函数的引用