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

how to separate tokens, using multiple ways

本文关键字:分离 令牌 方式 何使用      更新时间:2023-10-16

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

#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... nnPlease";
      cout <<" verify the file name and try againnn"<< 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 nn";
   }
   infile.close();
   system ("pause");
}

这就是它在文本文件中的内容。

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

第一个数字是选择二叉树,第二个数字是指它将插入树中的数字11和15(使用第一行)。然而,我的代码只读取每行中的前三个数字,我知道这是因为它是如何编程的,但我不知道如何选择其余的数字或令牌,不包括已经使用的前两个数字,然后创建一个二进制树,而不使用boost库。

我建议您对代码进行一些小的修改,它应该可以工作。不声明为字符串,而是声明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 nn";
}

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

  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
  }

看看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 nn";
    }
}

一旦您将其拆分,您就可以执行任意数量的操作。如果你正在构建一个从第三个到最后一个元素的二进制树,这就是迭代器对的伟大之处:

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