【问题标题】:C++ : Reading file and store data in multi-vectorC++:读取文件并将数据存储在多向量中
【发布时间】:2015-09-29 02:00:38
【问题描述】:

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

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);
    }

【问题讨论】:

    标签: c++ file vector


    【解决方案1】:

    因为你有

    CTransaction tran;
    

    在第一个 while 循环之外,项目不断添加到其中。将其移动到while 循环内。

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

    【讨论】:

      【解决方案2】:

      我按照你所说的 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);
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        相关资源
        最近更新 更多