如何使用多种方式分离令牌

how to separate tokens, using multiple ways

我有以下代码,目前可以使用。但是,我正在尝试以三种不同的方式读取令牌。第一个标记或数字是 select,第二个标记是 select 一个操作(插入或删除),字符串中的其余标记应该是要使用的值。该程序目前能够完成第一步和第二步,但我不知道如何 select 字符串中的其余标记作为用于创建二叉树的值。请帮忙

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include<sstream>

using namespace std;

struct trees {
   string typet;
   string nodes;
   string tree;
   trees *rec;
};

struct trees lines;
char line[50];
char* token;

int main()
{

   ifstream infile;
   infile.open("numbers.txt");
   if (!infile)
   {
      // If file doesn't exist.
      cout <<"File does not exist... \n\nPlease";
      cout <<" verify the file name and try again\n\n"<< endl;
   }

   while (infile.getline(line, 450))
   {
      string tree1, operation, data;
      istringstream liness(line);
      getline( liness, tree1,  ',' );
      getline( liness, operation, ',' );
      getline( liness, data,   ',' );
      //cout << linea  << endl;
      cout << "Type of tree: " << tree1 << " Operation to do: " << operation << " Data to use: " << data<< ".\n";
      //cout << line  << endl;

      if (tree1 == "1")
         cout<<"It is a binary tree \n\n";
   }

   infile.close();
   system ("pause");
}

这是文本文件中的内容。

1, 1, 10, 11, 15
1, 1, 13, 20, 14
1, 1, 3, 39. 18
1, 1, 3, 3, 16

第一个数字是 select 二叉树,第二个数字表示它将插入树编号 11 和 15(使用第一行)。但是我的代码只读取每一行的前三个数字,我知道这是因为它是如何编程的,但我不知道如何 select 其余数字或标记,不包括前两个已经使用过的数字,然后创建一个二叉树,而不是使用 boost 库。

看看boost::split:

while (infile.getline(line, 450))
{
    std::vector<std::string> tokens;
    boost::split(tokens, line, boost::is_any_of(","), boost::token_compress_on );

    // now just use the tokens
    if (tokens[0] == "1") {
        cout<<"It is a binary tree \n\n";
    }
}

拆分后,您可以进行任意数量的操作。如果您要构建从第 3 个元素到最后一个元素的二叉树,这就是迭代器对的好处:

assert(tokens.size() >= 3);
construct_binary_tree(tokens.begin() + 2, tokens.end());

我建议您对代码进行少量修改,它应该可以工作。不是声明为字符串,而是声明 tree1,将操作声明为整数,将数据声明为 int 大小为 3 的数组。

char ch;      //use this for comma
while (sampleFile.getline(line, 450))
{
    int tree1, operation, data[3];
    istringstream liness(line);
    //getline( liness, tree1,  ',' );
    //getline( liness, operation, ',' );
    //getline( liness, data,   ',' );
    //cout << linea  << endl;

    liness >> tree1 >> ch >> operation >> ch >> data[0] >> ch >> data[1] >> ch >> data[2];
    cout << "Type of tree: " << tree1 << " Operation to do: " << operation << " Data to use: " << data[0] << "," << data[1] << "," << data[2] << ".\n";

    if (tree1 == 1)    // remove quotes as comparing to integer
        cout<<"It is a binary tree \n\n";
}

编辑: 由于标记的数量不固定,假设文件中的数字以逗号分隔,您可以使用向量将数字插入其中。

  vector<int> data;
  string token;

  istringstream liness(lines);

  while(getline(liness,token,','))
  {
      int temp = stoi(token);       //convert string to int
      data.push_back(temp);         //insert into vector
  }