c++ - 如何使用多种方式分离 token

标签 c++ string token tokenize stringstream

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

#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

第一个数字是选择二叉树,第二个数字表示它将插入树编号 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 \n\n";
}

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

  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
  }

关于c++ - 如何使用多种方式分离 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29437438/

相关文章:

c# - c#如何通过索引提取字符串中的特定字符

php - Laravel 5 忽略身份验证特定路由

c++ - 我如何使用某种二进制签名识别 WinRAR SFX?

c++ - 如何避免单例?

java - 在java中交换字符串中的几个字符?

c++ - 二进制模式下的 std::ifstream 和 C++ 中的区域设置

c - 请解释书中的这一行 'The C Programming Language' Pg 192

azure - 如何修复 AzureADPreview Windows PowerShell 中的 'Policy operations on v2 application are disabled'

c++ - 默认选择第 0 个索引处的 QListWidget 项目

c++ - 在 eclipse c++ linux 中使用 opencv 静态库的大量 undefined reference 错误