【问题标题】:Reading variable sized columns in a matrix读取矩阵中可变大小的列
【发布时间】:2013-10-01 19:26:39
【问题描述】:

我有一个文件,其中包含不同行中的不同列。例如

10 20 30 60 
60 20 90 100 40 80
20 50 60 30 90
....

我想读取每行的最后三个数字。所以输出将是

20 30 60 
100 40 80
60 30 90

由于每行的大小可变,我无法使用以下结构

结构1:

std::ifstream fin ("data.txt");
while (fin >> a >> b >> c) {...}

结构2:

string line;
stringstream ss;
getline(fin, line);
ss << line;
int x, y, z;
ss >> x >> y >> z >> line;

那我该怎么办?

【问题讨论】:

    标签: c++ fstream getline


    【解决方案1】:

    将它们读入std::vector 并删除除最后 3 项之外的所有内容。

    std::string line;
    while (getline(fin, line))
    {
        std::vector<int> vLine;
        istringstream iss(line);
        std::copy(std::istream_iterator<int>(iss), std::istream_iterator<int>(), std::back_inserter(vLine));
        if (vLine.size() > 3)
        {
            vLine.erase(vLine.begin(), vLine.begin() + (vLine.size() - 3));
        }
        // store vLine somewhere useful
    }
    

    【讨论】:

    • 我必须先对行进行标记,问题是,我不知道每行中标记的确切数量
    猜你喜欢
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 1970-01-01
    • 2015-04-11
    • 1970-01-01
    • 2018-09-10
    相关资源
    最近更新 更多