如何将从文件中读取的行拆分为多个整数?

时间:2013-12-03 22:06:51

标签: c++ visual-c++

我收到了一个包含数字字符串的文件。我的目标是通过添加逗号和/等内容来重新格式化它们,因为数字行表示有关机器线下项目的信息。

这是我所拥有的,但我不确定从哪里开始:

void main()
{
    int num_dat_pts = 0, k;
    int id1, id2, day, month, year,
    shift, hour, minute, width, fraction, numbs;

    FILE * machine_samples_1;
    machine_samples_1 = fopen(filename, "r");
    fscanf(machine_samples_1, "%d%d%d%d%d%d%d%d", &id1, &id2, &day, &month, &year, &shift, &hour, &minute);

    fclose(machine_samples_1);
    getch();
}

2 个答案:

答案 0 :(得分:1)

更新回答见下文

要仅使用标准库分割一行,请使用stringstream:

#include <vector> // vector
#include <algorithm> // std::copy
#include <iterator>  // std::back_inserter and std::istream_iterator
#include <sstream>   // std::istringstream
#include <iostream>  // std::cout

int main()
{
    std::string line = "1 2 3 4 5 6 8 120";
    std::istringstream iss(line);

    std::vector<int> ints;
    std::copy(std::istream_iterator<int>(iss), {}, std::back_inserter(ints));

    std::cout << "parsed " << ints.size() << " integers: ";
    std::copy(ints.begin(), ints.end(), std::ostream_iterator<int>(std::cout, ";"));
}

查看 Live on Coliru

更新

如果您想将多行解析为id1,id2等的结构:

#include <boost/fusion/adapted/struct.hpp>
#include <boost/spirit/include/qi.hpp>
#include <fstream>
#include <iterator>

namespace qi = boost::spirit::qi;

struct DataPoint
{
    int id1;
    int id2;
    int day;
    int month;
    int year;
    int shift;
    int hour;
    int minute;
//  int width;
//  int fraction;
//  int numbs;
};

BOOST_FUSION_ADAPT_STRUCT(DataPoint, (int, id1)(int, id2)(int, day)(int, month)(int, year)(int, shift)(int, hour)(int, minute))

      //(int, width)
      //(int, fraction)
      //(int, numbs)

int main()
{
    std::ifstream machine_samples_1("filename");
    machine_samples_1.unsetf(std::ios::skipws);

    boost::spirit::istream_iterator first(machine_samples_1), last; 

    using qi::int_;
    std::vector<DataPoint> datapoints;
    bool ok = qi::phrase_parse(
            first, last, // input range
            (int_ >> int_ >> int_ >> int_ >> int_ >> int_ >> int_ >> int_) % qi::eol, // grammar
            qi::blank, // skipper
            datapoints);

    std::cout << "Parsed " << datapoints.size() << " data points";
}

还可以看到 Live on coliru

示例输出:

cat<<HERE >filename; clang++ -std=c++11 -Os main.cpp  && ./a.out
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
HERE
Parsed 3 data points

答案 1 :(得分:0)

由于您将此标记为C ++,如果您的文件内容如下所示:

1 2 3 4 5 6 7 8 9

然后你可以简单地编写这样的代码:

std::ifstream fin("myfile.txt");
std::string line;
if (std::getline(fin, line))
{
    int id1, id2, id3, id4, id5, id6, id7, id8, id9;
    std::istringstream iss(line);
    if (iss >> id1 >> id2 >> id3 >> id4 >> id5 >> id6 >> id7 >> id8 >> id9)
    {
        // do something with ids
    }
}