开发者

Need theory help with reading file and stuff

开发者 https://www.devze.com 2023-04-04 23:33 出处:网络
i would like to request some help on theory part, so grind those gears, here it comes I want to load a file into my program, which looks something like this:

i would like to request some help on theory part, so grind those gears, here it comes

I want to load a file into my program, which looks something like this:

0,10,10#0,100,40...

Okay what i now want to do is to take out every comma separated number and send it through my function

void func( int, float, float );

The hashtag means it's a new block, so it would be sent like func(0,10,10) and after that it would send func(0,100,40) and so on.

I was thinking to check every char until i meet ',' and after that put it in a vec开发者_开发百科tor, and continue that until the '#' is met. Then it would fire away my function (like func(v[0],v[1],v[2]) and then just do the same thing over and over until EOF!

Is this a good way to go? Have any better ideas? Those numbers can also get very large later on, so i don't know how much memory i need (therefor the vector). Or should i just go with 3 temp ints and floats and then fire the function and start over!


Going char by char and using a state machine like you suggested is the fastest way.
However the easiest way is first to split by the # and then for each result string split by ,.
You can use boost library to do the string split.


#include <fstream>
#include <ostream>
#include <istream>
#include <stdexcept>

void func( std::vector<float> &numbers )
{}

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

    float number;
    char seperator;
    std::vector<float> numbers;
    while( myfile >> number) { //read number
        numbers.push_back(number); //and remember it
        if (!(myfile >> seperator) || seperator == "#") { //if # or EOF or error
            func(numbers); //run function
            numbers.clear();  //and start over
        }
    } //only gets here at EOF or malformed file
    return 0;
}

Very simple, fast, and easy.


If you're certain the file starts with the first int of a group of three

ifstream fin("foo.csv");
string str;
stringstream s_str;
while(!fin.eof())
{
    int a;
    float b,c;
    getline(fin,str,',');
    s_str.str(str);
    s_str >> a;
    getline(fin,str,',');
    s_str.str(str);
    s_str >> b;
    getline(fin,str,'#');
    s_str.str(str);
    s_str >> c;
}

should work. (I haven't compiled it so there might be typos etc)

0

精彩评论

暂无评论...
验证码 换一张
取 消