从字符串中提取整数并转换为整数?

时间:2014-10-30 21:34:57

标签: c++

我有一个文本文件,如下所示:

Department Max
Bob 3 5 6 2 8 F1
Frank 4 8 8 8 8 F2
Jerry 7 9 9 0 9 F3
William 0 0 12 13 14 F2
Buck 3 4 10 8 8 4 6 F4
Greg 1 2 1 4 2 F1
Mike 3 4 4 8 4 F2

在忽略名称的同时,我如何阅读这些行并将这些整数作为单独的整数提取出来,以便我可以将它们一起添加?

到目前为止,我有这个:

for (int i = 0; i < 10; i++) //Loop that checks the employee and their paygrade, 10 times for 10 lines of data
    {
        getline(inFile, s); //Gets next line in Salary.txt
        string payGrade = s.substr(s.length() - 2, 2); //Checks the last two letters of the line to see paygrade
        if (payGrade == "F1")
        {
            auto pos = s.find(' ', s.find('"'));
            istringstream iss(s.substr(pos));


            F1employeeCounter++;
        }
        if (payGrade == "F2")
        {

            F2employeeCounter++;
        }
        if (payGrade == "F3")
        {

            F3employeeCounter++;
        }
        if (payGrade == "F4")
        {

            F4employeeCounter++;
        }
    }

基本上我必须检查什么类型的&#34;支付等级&#34;每个员工都是。有四种不同类型的薪酬等级:F1,F2,F3,F4,每种薪酬等级都有不同的方式根据工作时间支付员工。

2 个答案:

答案 0 :(得分:1)

下面是一个例子,说明如果你事先知道文件中文本的结构总是与你的例子中看起来一样,它是如何完成的。

传统上,在C ++中使用Streams来解析文本中的数据(例如整数)。在这种情况下,包含std::istream_iterator的流迭代器std::istringstream用于解析整数标记。此外,标准算法std::accumulate用于对已解析的整数求和。

std::ifstream input{"my_file"};

// For every line read:
for (std::string line; std::getline(input, line);) {
    // Find position of first space after first citation character (").
    auto pos = line.find(' ', line.find('"'));

    // Use position to copy relevant numbers part into a string stream.
    std::istringstream iss{line.substr(pos)};

    // Accumulate sum from parsed integers.
    auto sum = std::accumulate(std::istream_iterator<int>{iss}, 
                               std::istream_iterator<int>{},
                               0);

    /* Do something with sum... */
}

Live example

答案 1 :(得分:0)

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    std::istringstream iss("Bo 3 3 6 2 8\nFred 7 8 5 8 8\nJosh 7 9 4 0 1");

    while (iss.good()) //will exit this loop when there is no more text to read
    {
        std::string line;

        //extract next line from iss
        std::getline(iss, line);

        //construct string stream from extracted line
        std::stringstream ss(line);

        std::string name;
        int sum = 0;
        int i = 0;

        //extract name
        ss >> name;

        while(ss.good())
        {
            //extract integer
            ss >> i;

            //add to the sum
            sum += i;
        }

        //output name and sum
        std::cout << name << ":" << sum << std::endl;
    }
}

输出:

Bo:22
Fred:36
Josh:21