Code: read numeric values with C++. From file to array.

Here is a small C++ piece of code for those who need to read some numeric values from files.
My file format is bellow; scientific notation, commented lines.. etc.
# Time	Cd	Cl	Cm
1	-660.486	1.0285	-0.239618
2	-326.356	-1.86631	0.047646
3	166.242	-1.14998	0.0979555
4	235.177	0.835717	-0.0900095
25	-5.1296	0.303168	-0.191563
75	-5.11033	0.0031427	-2.12211e-05
76	-5.09629	0.00546416	-0.00169277
77	-5.09693	0.00482644	-0.0037029
Here is a generic code witch works this my format, probably needs some small modifications for you.

/*
 * =====================================================================================
 *
 *       Filename:  readData.cpp
 *
 *    Description:  Programa para almacenar valores numericos tomados de un fichero
 *                  Soporta notacion cientifica (e-01) y lineas comentadas.
 *
 *        Version:  1.0
 *        Created:  10/01/13 10:57:22
 *       Revision:  0
 *       Compiler:  g++
 *
 *         Author:  Samuel Rodriguez Bernabeu (srodrb), srodrb@gmail.com
 *   Organization:  University of Leon (Spain)
 *
 * =====================================================================================
 */

#include <iostream>
#include <fstream>
#include <string>
#include <math.h>  // necesaria para pow
#include <cstdlib> // para atof en c++
using namespace std;

int main(int argc, const char *argv[])
{
//============================== Function arguments
string commentSymbol = "#";
const char* filename = "forceCoeffs/0/forceCoeffs.dat";
//============================== end of function arguments

string STRING;
string value;
string exp; //contiene el numero
int expValue = 0;
int numberOfLines = 0;
string previousLine="";
int numberOfValues = 1;

ifstream infile;
infile.open (filename);
if(!infile){printf("ERROR: cannot open %s\n", filename );}

while(!infile.eof())
{
    getline(infile,STRING);

    if ((STRING != previousLine) && (STRING[0] != commentSymbol[0]))
    {
        numberOfLines++;

        if(numberOfLines == 1)
        {
            for (int i = 0; i < STRING.size()-1; i++) {
                if( isspace(STRING.at(i)) )
                {
                    numberOfValues++;
                }
            }
        }

        previousLine=STRING;
    }
}

numberOfLines--;
infile.close();

float values[numberOfLines][numberOfValues];
int column = 0;
int row = 0;

infile.open (filename);
if(!infile){printf("ERROR: cannot open %s\n", filename );}

while(!infile.eof())
{
    getline(infile,STRING);
    if (STRING != previousLine)
    {
        if( STRING[0] != commentSymbol[0] )
        {
            for (int i = 0; i < STRING.size(); i++) {

                if (!isspace(STRING.at(i))){

                    if(STRING.at(i) == 'e')
                    {
                        i++;
                        while( !isspace(STRING.at(i))) {
                            exp.append(STRING,i,1);
                            i++;
                            expValue = atoi(exp.c_str());
                            if(i == STRING.size()){goto endLoop;}
                        }
                    }

                    else{
                        value.append(STRING,i,1);
                        if(i==STRING.size()-1){goto endLoop;}
                    }
                }

                else{
                    endLoop:

                    values[row-1][column] =
                                     (double)strtod(value.c_str(),NULL)*
                                     (pow(10,expValue));
                    expValue = 0;
                    column++;
                    value.clear();
                    exp.clear();

                    }
            }
        }
        column = 0;
        row++;
    }
}

row = row-1; // non out-of-bounds condition
return 0;
}
Here is the output showing the array values:

1  -660.486  1.0285  -0.239618
2  -326.356  -1.86631  0.047646
3  166.242  -1.14998  0.0979555
4  235.177  0.835717  -0.0900095
25  -5.1296  0.303168  -0.191563
75  -5.11033  0.0031427  -2.12211e-05
76  -5.09629  0.00546416  -0.00169277
77  -5.09693  0.00482644  -0.0037029

Esta entrada fue publicada en C/C++, OpenFOAM y etiquetada , , . Guarda el enlace permanente.

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s