在多向量中读取文件和存储数据

C++ : Reading file and store data in multi-vector

本文关键字:存储 数据 文件 读取 向量      更新时间:2023-10-16

我正在尝试用这种格式读取数据文件

T1: I1,I2,I5 
T2: I2,I4 
T3: I2,I3 
T4: I1,I2,I4 
T5: I1,I3 
T6: I2,I3 
T7: I1,I3 
T8: I1,I2,I3,I5 
T9: I1,I2,I3 

我不想读第一列T1,T2,T3 ......,但是每行都将是一个数据集,我想在(空格' ')之后开始读取并以每行结束,以及我如何根据(逗号',')分隔数据

我写了这段代码,但它没有正常工作,它读取第一列

string CItem;
// set of elements
set< CItem > CItemSet;
//Transactions
 CItemSet CTransaction;
// set of transactions
vector< CTransaction > CTransactionSet;
ifstream inFile(inFileName);
    if (!inFile)
    {
        cout << "Failed to open input file filename:." << inFileName;
    }
CTransactionSet transSet;
    CTransaction tran;
    string txtLine;
    // read every line from the stream
    while (getline(inFile, txtLine))
    {
        istringstream txtStream(txtLine);
        string txtElement;
        // read every element from the line that is seperated by commas
        // and put it into the vector or strings
        while (getline(txtStream, txtElement, ','))
        {
            if (txtElement == ": ") break;
            else tran.insert(txtElement);
        }
        transSet.push_back(tran);
    }

既然你有

CTransaction tran;

在第一个while循环之外,项目继续被添加到它。把它移到while循环中

CTransactionSet transSet;
string txtLine;
// read every line from the stream
while (getline(inFile, txtLine))
{
    CTransaction tran;

我通过做你说的R Sahu来解决这个问题,但最重要的解决方案是使用。ignore,这样我们就不会读取' '之前的部分

CTransactionSet transSet;
    string txtLine;
    // read every line from the stream
    while (getline(inFile, txtLine))
    {
        istringstream txtStream(txtLine);
        txtStream.ignore(txtLine.length(), ' ');
        // read every element from the line that is seperated by commas
        // and put it into the vector or strings
        string txtElement;
        CTransaction tran;
        while (getline(txtStream, txtElement, ','))
        {
            tran.insert(txtElement);
        }
        transSet.push_back(tran);
    }