将单个整数的集合解析为浮点数

parse collection of single integers into floats

所以我在一个包含数字的文件中吞咽了一下:39.00 变成了 vector<std::string> 现在我需要将看起来像 3 9 0 0 的数字组转换回 39.00 的形式

这是一个小样本。

3 4 5 0 1 2 5 0 3 4 0 0 3 4 9 0 7 0 0 0 8 0 0 0 9 0 0 0 6 5 0 0 3 9 3 2 1 1 2 0 0 0 2 5 0 0 3 0 9 0 4 0 0 0 5 5 5 0 2 0 0 0 2 5 0 0 3 0 9 0 4 0 0 0 5 5 5 0 2 2 3 0 0 0 2 4 0 0 4 5 0 0 6 7 0 0 6 5 5 0 5 6 9 0 8 7 0 0 4 3 5 0 5 6 9 8 5 5 4 0 3 3 6 2 0 0 3 4 5 0 1 2 5 0 3 4 0 0 3 4 9 0 7 0 0 0 8 0 0 0 9 0 0 0 6 5 0 0 3 9 0 3 2 1 1 2 0 0 0 2 5 0 0 3 0 9 0 4 0 0 0 5 5 5 0 2 0 0 0 2 5 0 0 3 0 9 0 4 0 0 0 5 5 5 0 2 2 3 0 0 0 2 4 0 0 4 5 0 0 6 7 0 0 6 5 5 0 5 6 9 0 8 7 0 0 4 3 5 0 5 6 9 8 5 5 4 0 3 3 6 2 0 0 3 4 5 0 1 2 5 0 3 4 0 0 3 4 9 0 7 0 0 0 8 0 0 0 9 0 0 0 6 5 0 0 3 9 0 0 

转换为 34.50 12.50 34.00....

我的目标是最终找到所有浮点数的平均值。

当然,如果有一种方法可以在仅使用标准库保留格式的同时压缩文件,那也很酷。

#include <iostream>
#include <string>
#include <fstream>
#include <streambuf>
#include <regex>
#include <vector>
#include <math.h>

void tableWriter(std::string);
float employeeAverage(std::string);
float employeeTotal(std::string);
float totalAverage(std::string);

void totalPayroll(std::string, std::vector<std::string>);


std::string getEmployeeName(std::string, std::string[]);


int main(int argc, const char * argv[]) {
    try {
    std::vector<std::string> regexContainer;

    std::ifstream t("TheSales.txt");
    std::string theSales;

    t.seekg(0, std::ios::end);
    theSales.reserve(t.tellg());
    t.seekg(0, std::ios::beg);

    theSales.assign((std::istreambuf_iterator<char>(t)),
               std::istreambuf_iterator<char>());

    //std::cout << theSales << std::endl;

    totalPayroll(theSales, regexContainer);
    std::cout << std::endl << regexContainer.empty() << std::endl;

    return 0;
    } catch (int w) {
        std::cout << "Could not open file. Exiting Now." << std::endl; return 0;
    }
}


void tableWriter(std::string){}
float employeeAverage(std::string){return 0.0;}
float employeeTotal(std::string){return 0.0;}
float totalAverage(std::string){return 0.0;}



void totalPayroll(std::string theSales, std::vector<std::string> regexContainer) {

    std::string matches;
    std::regex pattern ("\d");

    const std::sregex_token_iterator end;
    for (std::sregex_token_iterator i(theSales.cbegin(), theSales.cend(), pattern);
         i != end;
         ++i)
    {
        regexContainer.push_back(*i);
        for (std::vector<std::string>::const_iterator i = regexContainer.begin(); i != regexContainer.end(); ++i)
            std::cout << *i << ' ';
    }


}

这是数据:

2.40 5.30 6.30 65.34 65.34
3.40 7.80 3.20 65.34 65.34
3.40 5.20 8.20 23.54 12.34
2.42 5.30 6.30 5.00  65.34
3.44 7.80 3.20 34.55 65.34
3.45 5.20 8.20 65.34 65.34

fscanf 等函数能够从您的文件中读取 return 格式正确的浮点数。这应该比尝试从字符流中重建它们更有效...