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

parse collection of single integers into floats

本文关键字:浮点数 集合 单个 整数      更新时间:2023-10-16

因此,我在一个文件中添加了数字,其中包括:39.00vector<std::string>,现在我需要将看起来像39 00的数字组转换回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能够从文件中读取并返回正确格式的浮点数。这应该比尝试从char…

的流中重建它们更有效。