c++ - 在 C 或 C++ 中解析具有可变条目数的行(无提升)

标签 c++ c parsing

我有一个 file包含表格的行,

double mass, string seq, int K, int TS, int M, [variable number of ints]
688.83       AFTDSK      1      1       0       3384 2399 1200
790.00       MDSSTK      1      3       1       342 2

我需要一种(最好是简单的)方法来解析这个文件而无需提升。如果每行值的数量一直不变,那么我会使用解决方案 here .

每一行都将成为 Peptide 类的一个对象:

class Peptide {
    public:
        double mass;
        string sequence;
        int numK;
        int numPTS;
        int numM;
        set<int> parents;
 }

前三个整数在对象中有特定的变量名,而后面的所有整数都需要插入到一个集合中。


我很幸运得到了两个非常棒的响应,但运行时差异使 C 实现对我来说是最好的答案。

最佳答案

如果您想使用 C++,请使用 C++:

std::list<Peptide> list;
std::ifstream file("filename.ext");

while (std::getline(file, line)) {

    // Ignore empty lines.
    if (line.empty()) continue;

    // Stringstreams are your friends!
    std::istringstream row(line);

    // Read ordinary data members.
    Peptide peptide;
    row >> peptide.mass
        >> peptide.sequence
        >> peptide.numK
        >> peptide.numPTS
        >> peptide.numM;

    // Read numbers until reading fails.    
    int parent;
    while (row >> parent)
        peptide.parents.insert(parent);

    // Do whatever you like with each peptide.
    list.push_back(peptide);

}

关于c++ - 在 C 或 C++ 中解析具有可变条目数的行(无提升),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3115146/

相关文章:

c++ - 纯 Win32 C++ 中的自定义菜单边框(无 WTL、MFC 等)

c++ - 接受用户输入的字符并按出现的降序显示它们的程序

parsing - 如何编写标识符可以以关键字开头的词法分析器?

c# - 无法使用 Linq 访问特定的 XML 文件 block

Python字符串范围(解析html)

c++ - 编译器如何选择正确的重载函数?

c++ - SDL DevC++ 链接器问题

c - 通过在 C 中执行 "string"+ 1 来截断

java - 将C代码改成JAVA代码【神经网络】

c - 在 pci 设备驱动程序中实现读/写 file_operations