How to read numbers from an ASCII file (C++)

后端 未结 4 1652
梦如初夏
梦如初夏 2021-01-31 19:48

I need to read in data files which look like this:

* SZA: 10.00
 2.648  2.648  2.648  2.648  2.648  2.648  2.648  2.649  2.650  2.650
 2.652  2.653  2.652  2.653         


        
4条回答
  •  孤街浪徒
    2021-01-31 20:32

    I would do something like this:

    std::ifstream input("input.txt");
    std::vector floats;
    std::string header;
    std::getline(input, header); // read in the "* SZA: 10.00" line
    if(header_is_correct(header)) {
        float value;
        // while we could successfully read in a float from the file...
        while(input >> value) {
            // store it in the vector.
            floats.push_back(value);
        }
    }
    

    NOTE: header_is_correct(header) is just an example, you will need to implement any error checking for that first line manually there.

提交回复
热议问题